Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using UnityEngine;
using Unity.Collections;
using Unity.Jobs;
public class NativeListExample : MonoBehaviour
{
JobHandle handle;
NativeQueue<int> queue;
NativeList<int> list;
private void Awake()
{
queue = new NativeQueue<int>(Allocator.Persistent);
list = new NativeList<int>(8, Allocator.Persistent);
}
private void OnDestroy()
{
handle.Complete();
queue.Dispose();
list.Dispose();
}
void Update()
{
handle.Complete();
ResetCollections();
handle = new AddJob { queue = queue, list = list }.Schedule();
handle = new UpdateJob {
array = list.AsDeferredJobArray() // AsDeferredJobArrayでNativeArrayにする
}.Schedule(list, 4, handle); // 要素数の部分にはlistを登録
handle = new ShowLogJob{ list = list }.Schedule(list, 1, handle);
JobHandle.ScheduleBatchedJobs();
}
void ResetCollections()
{
// Listに登録する要素を追加
queue.Enqueue(3); queue.Enqueue(2);
queue.Enqueue(4); queue.Enqueue(5);
// リストをクリア
list.Clear();
}
struct AddJob : IJob
{
public NativeQueue<int> queue;
public NativeList<int> list;
public void Execute()
{
while (queue.TryDequeue(out int item))
{
if (item % 2 == 0) // 2で割り切れる要素だけ追加
list.Add(item);
}
}
}
struct UpdateJob : IJobParallelFor
{
public NativeArray<int> array;
public void Execute(int index)
{
array[index] += 1;
}
}
struct ShowLogJob : IJobParallelFor
{
[ReadOnly] public NativeList<int> list;
public void Execute(int index)
{
Debug.Log(list[index]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.