Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using Unity.Collections;
using Unity.Jobs;
using UnityEngine;
public class AllocTest : MonoBehaviour
{
GetResultJob job;
JobHandle handle;
void Update ()
{
var size = Random.Range(1000, 10000);
// 毎フレームNativeArrayを生成
var array1 = new NativeArray<int>(size, Allocator.TempJob);
var plusHandle = new PlusJob() { array = array1 }.Schedule(size, 64);
job = new GetResultJob() { array = array1, result = new NativeArray<int>(1, Allocator.Temp) };
handle = job.Schedule(plusHandle);
}
void LateUpdate()
{
handle.Complete();
var result = job.result[0];
job.result.Dispose(); // resultはtempなので自分で開放する
Debug.Log(result);
}
[ComputeJobOptimization]
struct PlusJob : IJobParallelFor
{
public NativeArray<int> array;
public void Execute(int index)
{
array[index]++;
}
}
[ComputeJobOptimization]
struct GetResultJob : IJob
{
[DeallocateOnJobCompletion]
[ReadOnly] public NativeArray<int> array; // arrayは自動的に開放する
[WriteOnly] public NativeArray<int> result;
public void Execute()
{
int res = 0;
for(int i=0; i<array.Length; i++)
res += array[i];
result[0] = res;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment