什么是Chunk?
Chunk:拥有相同Component的Entity的集合
Archetype:Chunk容量有限,一系列同样大小的Chunk组成Archetype
因为拥有相同Component的Entity都存储在Chunk中,所以ECS规定:创建/销毁实体、添加/删除组件,都不能在在Job中处理。否则其他Job不知道,会引起错误。
第一个例子中的System,是在主线程中使用ForEach逐个Entity更新数据;而使用Chunk可以结合Job批量处理,速度更快:
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
public struct RotationSpeed : IComponentData
{
public float Speed;
}
public class ChunkSystem : SystemBase
{
// Job
struct RotationJob : IJobChunk
{
public ArchetypeChunkComponentType<Rotation> RotationType;
public ArchetypeChunkComponentType<RotationSpeed> RotationSpeedType;
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
{
var chunkRotations = chunk.GetNativeArray(RotationType);
var chunkRotationSpeeds = chunk.GetNativeArray(RotationSpeedType);
// 遍历Chunk中的Entity
for (var i = 0; i < chunk.Count; i++)
{
chunkRotations[i] = new Rotation
{
Value = math.mul(
math.normalize(chunkRotations[i].Value),
quaternion.AxisAngle(math.up(), chunkRotationSpeeds[i].Speed))
};
}
}
}
EntityQuery queriedEntity;// 实体筛选器
protected override void OnCreate()
{
// 筛选实体
queriedEntity = GetEntityQuery(typeof(Rotation), typeof(RotationSpeed));
}
protected override void OnUpdate()
{
var rotationType = GetArchetypeChunkComponentType<Rotation>();
var rotationSpeedType = GetArchetypeChunkComponentType<RotationSpeed>();
// 创建Job
var job = new RotationJob()
{
RotationType = rotationType,
RotationSpeedType = rotationSpeedType
};
// 对筛选出的使用Job
Dependency = job.Schedule(queriedEntity, Dependency);
}
}