Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Last active May 21, 2018 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsubaki/dcb571395e1f61827fbfe9812a7c4a5e to your computer and use it in GitHub Desktop.
Save tsubaki/dcb571395e1f61827fbfe9812a7c4a5e to your computer and use it in GitHub Desktop.
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