ReadOnlyAttribute

class in Unity.Collections

切换到手册

描述

借助 ReadOnly 属性,您可以将作业中所用结构的某个成员标记为只读。

在作业中使用原生容器时,这些容器在默认情况下处于读写状态。这意味着,您无法同时安排两个作业来引用相同的容器。通过向作业结构中的容器字段添加 [ReadOnly] 属性,将容器标记为只读,这样一来,两个作业可以并行运行,并从同一容器中读取数据。

另请参阅:IJobIJobParallelFor

using Unity.Jobs;
using Unity.Collections;
using UnityEngine;

public struct MyJob : IJob { [ReadOnly] public NativeArray<int> input;

public NativeArray<int> output;

public void Execute() { for (var i = 0; i < output.Length; ++i) output[i] = input[i]; } }

public class ParallelReplicator : MonoBehaviour { public void OnUpdate() { const int n = 10000; var original = new NativeArray<int>(n, Allocator.Persistent); var clone1 = new NativeArray<int>(n, Allocator.Persistent); var clone2 = new NativeArray<int>(n, Allocator.Persistent);

var job1 = new MyJob { input = original, output = clone1 }; var job2 = new MyJob { input = original, output = clone2 };

var jobX = new MyJob { input = original, output = clone2 };

// Run the jobs in parallel. var jobs = JobHandle.CombineDependencies(job1.Schedule(), job2.Schedule());

// jobX.Schedule(); // Not allowed, throws exception because job2 is writing into copy2.

jobs.Complete();

jobX.Schedule().Complete(); // Allowed, because job2 has been completed by now.

original.Dispose(); clone1.Dispose(); clone2.Dispose(); } }