创造Job
要在Unity中创建Job,您需要实现IJob接口。IJob使您可以计划与其他正在运行的Job并行运行的单个Job。
注意:“Job”是Unity中所有实现该IJob接口的struct的统称。
要创建Job,您需要:
- 创建一个struct实现接口IJob。
- 添加Job使用的成员变量(blittable 类型或NativeContainer类型)。
- 在struct中创建一个名为Execute的方法,并在其中执行Job(也就是实际要做的事情)。
- 执行Job时,该Execute方法在单个内核上运行一次(应该是被分配的cpu上某个核上)。
注意:在设计Job时,请记住,它们对数据副本起作用,除非使用NativeContainer。因此,从主线程中的Job访问数据的唯一方法是写入NativeContainer。
举一个简单的Job定义的栗子
// Job adding two floating point values together
public struct MyJob : IJob
{
public float a;
public float b;
public NativeArray<float> result;
public void Execute()
{
result[0] = a + b;
}
}
安排Job(Scheduling Job)
要在主线程中安排Job,您必须:
- 实例化Job。
- 给Job的添加数值(其实是对Job中定义的数据赋值或者叫初始化数据)。
- 调用Schedule方法。
- 调用Schedule会将Job放入Job队列以在适当的时间执行。安排Job后,您将无法中断Job。
注意:您只能从主线程调用Schedule方法。
接上一个创建Job的例子举一个安排Job的栗子
// Create a native array of a single float to store the result. This example waits for the job to complete for illustration purposes
NativeArray<float> result = new NativeArray<float>(1, Allocator.TempJob);
// Set up the job data
MyJob jobData = new MyJob();
jobData.a = 10;
jobData.b = 10;
jobData.result = result;
// Schedule the job
JobHandle handle = jobData.Schedule();
// Wait for the job to complete
handle.Complete();
// All copies of the NativeArray point to the same memory, you can access the result in "your" copy of the NativeArray
float aPlusB = result[0];
// Free the memory allocated by the result array
result.Dispose();