Version: 2020.2
언어: 한국어

ReadOnlyAttribute

class in Unity.Collections

매뉴얼로 전환

설명

The ReadOnly attribute lets you mark a member of a struct used in a job as read-only.

Native containers are read-write by default when used in a job. This means that you cannot schedule two jobs referencing the same containers simultaneously. By adding the ReadOnly attribute to the container field in the job struct the container is marked as read-only, which allows two jobs to run in parallel reading data from the same container.

See Also: IJob, IJobParallelFor.

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(); } }