Unity Job System 入门

Job System

  • IJobParallelFor

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using Unity.Burst;
using Unity.Jobs;

public static class JobRandomTest
{
[BurstCompile(CompileSynchronously = true)]
private struct JobForRandom : IJobParallelFor
{
private readonly uint m_seed;
public NativeArray<float> Result;

public JobForRandom(NativeArray<float> result, uint seed = 3)
{
Result = result;
m_seed = seed;
}

public void Execute(int index)
{
Random rnd = Random.CreateFromIndex((uint) (index + m_seed));
Result[index] = rnd.NextFloat(0, 100);
}
}

public static void Execute(uint seed)
{
var container = new NativeArray<float>(100, Allocator.TempJob);

JobForRandom job = new JobForRandom(container, seed);
JobHandle jobHandle = job.Schedule(container.Length, 1);
jobHandle.Complete();

var result = job.Result.ToList();

foreach(var r in result)
{
Debug.Log(r);
}

job.Result.Dispose();
}
}

参考


Unity Job System 入门
https://automask.github.io/wild/2022/06/28/lab/S_Unity_JobSystem/
作者
Kyle Zhou
发布于
2022年6月28日
许可协议