Method AsDeferredJobArray
AsDeferredJobArray()
Returns an array that aliases this list. The length of the array is updated when the length of this array is updated in a prior job.
Declaration
public NativeArray<T> AsDeferredJobArray()
Returns
Type | Description |
---|---|
Native |
An array that aliases this list and whose length can be specially modified across jobs. |
Remarks
Useful when a job populates a list that is then used by another job.
If you pass both jobs the same list, you have to complete the first job before you schedule the second: otherwise, the second job doesn't see the first job's changes to the list's length.
If instead you pass the second job a deferred array that aliases the list, the array's length is kept in sync with the first job's changes to the list's length. Consequently, the first job doesn't have to be completed before you can schedule the second: the second job simply has to depend upon the first.
Examples
The following example populates a list with integers in one job and passes that data to a second job as a deferred array. If we tried to pass the list directly to the second job, that job would not see any modifications made to the list by the first job. To avoid this, we instead pass the second job a deferred array that aliases the list.
using UnityEngine;
using Unity.Jobs;
using Unity.Collections;
public class DeferredArraySum : MonoBehaviour
{
public struct Populate : IJob
{
public NativeList<int> list;
public void Execute()
{
for (int i = list.Length; i < list.Capacity; i++)
{
list.Add(i);
}
}
}
// Sums all numbers from deferred.
public struct Sum : IJob
{
[ReadOnly] public NativeArray<int> deferred;
public NativeArray<int> sum;
public void Execute()
{
sum[0] = 0;
for (int i = 0; i < deferred.Length; i++)
{
sum[0] += deferred[i];
}
}
}
void Start()
{
var list = new NativeList<int>(100, Allocator.TempJob);
var deferred = list.AsDeferredJobArray(),
var output = new NativeArray<int>(1, Allocator.TempJob);
// The Populate job increases the list's length from 0 to 100.
var populate = new Populate { list = list }.Schedule();
// At time of scheduling, the length of the deferred array given to Sum is 0.
// When Populate increases the list's length, the deferred array's length field in the
// Sum job is also modified, even though it has already been scheduled.
var sum = new Sum { deferred = deferred, sum = output }.Schedule(populate);
sum.Complete();
Debug.Log("Result: " + output[0]);
list.Dispose();
output.Dispose();
}
}