由于可能会使用多线程,需要定义字段存储数据,然后统一执行 Excute() 进行运算。
另外Job可继承自多种接口,各接口参数不同,需要自定义字段用以实现。
1. IJobForeach<T1,T2,T3,…>
简单地绑定ComponentData类型
public struct Job : IJobForEach<SpriteSheetAnimation_Data, Translation>
{
//任何可能的数据
public float DeltaTime;
public void Execute(ref SpriteSheetAnimation_Data spriteSheetAnimationData, ref Translation translation)
{
}
}
{
job.Schedule(ComponentSystemBase systemBase, JobHandle handle)
}
2. IJobEntityBatch
合批处理,适用于大量/分批操作数据
struct RotationSpeedJob : IJobEntityBatch
{
public float DeltaTime;
public ComponentTypeHandle<Rotation> RotationTypeHandle;
[ReadOnly] public ComponentTypeHandle<RotationSpeed_IJobEntityBatch> RotationSpeedTypeHandle;
public void Execute(ArchetypeChunk batchInChunk, int batchIndex)
{
var chunkRotations = batchInChunk.GetNativeArray(RotationTypeHandle);
var chunkRotationSpeeds = batchInChunk.GetNativeArray(RotationSpeedTypeHandle);
for (var i = 0; i < batchInChunk.Count; i++)
{
var rotation = chunkRotations[i];
var rotationSpeed = chunkRotationSpeeds[i];
// Rotate something about its up vector at the speed given by RotationSpeed_IJobChunk.
chunkRotations[i] = new Rotation
{
Value = math.mul(math.normalize(rotation.Value),
quaternion.AxisAngle(math.up(), rotationSpeed.RadiansPerSecond * DeltaTime))
};
}
}
}
{
job.ScheduleParallel(EntiyQuery query, int batchCountPerChunk, JobHandle handle);
}
3. IJobChunk
主线程的OnUpdate也可以进行Burst加速
struct RotationSpeedJob : IJobChunk
{
public float DeltaTime;
public ComponentTypeHandle<Rotation> RotationTypeHandle;
[ReadOnly] public ComponentTypeHandle<RotationSpeed_IJobChunkStructBased> RotationSpeedTypeHandle;
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
{
var chunkRotations = chunk.GetNativeArray(RotationTypeHandle);
var chunkRotationSpeeds = chunk.GetNativeArray(RotationSpeedTypeHandle);
for (var i = 0; i < chunk.Count; i++)
{
var rotation = chunkRotations[i];
var rotationSpeed = chunkRotationSpeeds[i];
// Rotate something about its up vector at the speed given by RotationSpeed_IJobChunkStructBased.
chunkRotations[i] = new Rotation
{
Value = math.mul(math.normalize(rotation.Value),
quaternion.AxisAngle(math.up(), rotationSpeed.RadiansPerSecond * DeltaTime))
};
}
}
}
{
job.ScheduleSingle(EntityQuery query,JobHandle handle)
}
4. IJobParalleFor
大量数据,多线程并行,可细分接口类型
public struct ReallyToughParalleJob : IJobParallelFor
{
//需要数组字段存储数据,用以运算
public void Execute(int index){}
}
job.Schedule(int arrayLength,int batchCount);
细分接口如IJobParallelForTransform
public struct ReallyToughParalleJobTransforms : IJobParallelForTransform
{
public void Execute(int index, TransformAccess transform) {}
}
job.Schedule(TransformAccesseArray array);