升级Unity版本到2020.1或更高版本,同时更新Burst编译器版本。 代码示例:
// Burst编译器访问方法声明
[BurstCompile]
void MethodToCompileWithBurst()
{
// 方法体
}
// 引用名为"Unity.Burst"的命名空间
using Unity.Burst;
// 引用名为"Unity.Collections"的命名空间
using Unity.Collections;
// 引用名为"Unity.Mathematics"的命名空间
using Unity.Mathematics;
public class SomeClass
{
void SomeMethod()
{
// 使用多线程进行数组处理
var array = new NativeArray(100, Allocator.TempJob);
// 申请一个job,执行数组处理
var job = new ArrayJob
{
Array = array,
FloatValue = 5.0f
};
// 通过Burst编译器进行处理
var jobHandle = job.Schedule(array.Length, 1);
// 等待处理完成
jobHandle.Complete();
// 处理结果处理
for (int i = 0; i < array.Length; i++)
Debug.Log(array[i]);
// 处理结束,释放资源
array.Dispose();
}
// Job struct
[BurstCompile]
public struct ArrayJob : IJobParallelFor
{
public NativeArray Array;
public float FloatValue;
public void Execute(int index)
{
Array[index] = FloatValue * index;
}
}
}