Unity ECS 进阶——使用Chunk批量操作实体

什么是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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值