Created
February 24, 2019 13:44
-
-
Save tsubaki/5f1b68b0ddfb3fc948078d280773b928 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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