安装ECS在PackageManager中搜索并安装Entities Graphics烘焙Entitypublic class FallingCubeSpawnerAuthoring : MonoBehaviour { public class Baker : BakerFallingCubeSpawnerAuthoring { public override void Bake(FallingCubeSpawnerAuthoring authoring) { Entity spawnerEntity GetEntity(TransformUsageFlags.None); } } }烘焙显示在场景中的物体用TransformUsageFlags.Dynamic构建Component创建所有Component必须继承IComponentData标签public struct CreatCubeTag : IComponentData { }数据public struct FallingCubeSpawner : IComponentData { public Entity CubePrefab; public int MaxCount; }赋值public class FallingCubeSpawnerAuthoring : MonoBehaviour { [SerializeField] private GameObject cubePrefab; [SerializeField] private int maxCount 1000; public class Baker : BakerFallingCubeSpawnerAuthoring { public override void Bake(FallingCubeSpawnerAuthoring authoring) { Entity spawnerEntity GetEntity(TransformUsageFlags.None); Entity cubePrefabEntity GetEntity( authoring.cubePrefab, TransformUsageFlags.Dynamic ); AddComponentCreatCubeTag(spawnerEntity); AddComponent(spawnerEntity, new FallingCubeSpawner { CubePrefab cubePrefabEntity, MaxCount authoring.maxCount, }); } } }创建System框架public partial struct FallingCubeSystem : ISystem { public void OnCreate(ref SystemState state) { state.RequireForUpdateFallingCubeSpawner(); } public void OnUpdate(ref SystemState state) { float deltaTime SystemAPI.Time.DeltaTime; EntityCommandBuffer ecb new EntityCommandBuffer(state.WorldUpdateAllocator); //todo 这里写工作流 ecb.Playback(state.EntityManager); ecb.Dispose(); } }state.RequireForUpdateFallingCubeSpawner();泛型传入参数代表烘焙场景中存在指定组件才会执行Update可以执行多次添加多次float deltaTime SystemAPI.Time.DeltaTime;获取每一帧的时间间隔EntityCommandBuffer ecb new EntityCommandBuffer(state.WorldUpdateAllocator);创建ecb对象工作流中需要使用Entity的删除与创建激活与隐藏添加和删除组件都需要走ecb这里自己实例化了一个在涉及到物理的System当中不能这么用ecb.Playback(state.EntityManager); ecb.Dispose();调用ecb并释放ecb通常一起使用处理工作流中注册的对于Entity的操作然后释放自己实例化的ecb对象需要手动调用不调用会出错工作流创建工作流[BurstCompile] [WithAll(typeof(CreatCubeTag))] public partial struct CreatCubeJob : IJobEntity { public int countNow; public EntityCommandBuffer.ParallelWriter Ecb; void Execute([EntityIndexInQuery]int sortKey, ref FallingCubeSpawner cubeValue) { if (countNow cubeValue.MaxCount) { Entity cube Ecb.Instantiate(sortKey,cubeValue.CubePrefab); float randomX new Random().NextFloat(-10f, 10f); Ecb.SetComponent(sortKey, cube, LocalTransform.FromPosition(new float3(randomX, 20f, 0f)) ); } } }工作流必须继承IJobEntity基类然后实现Execute方法方法参数任意如果涉及到操作Entity物体激活或隐藏创建或释放则需要在类中创建参数public EntityCommandBuffer.ParallelWriter Ecb;ecb是操作Entity物体的关键然后还需要在Execute方法指定第一个参数为void Execute([EntityIndexInQuery]int sortKey)其中[EntityIndexInQuery]标签为必添加的这个标签添加以后这个变量能够自动赋值每次调用ecb的时候都需要传入这个参数用来指定在ecb中逻辑执行的顺序如果不传或者传0会出现代码顺序错乱的问题然后仔细讲一下Execute方法这个方法在工作流中会自动执行根据参数筛选需要被处理的Entity同时除了带有比如[EntityIndexInQuery]标签的顺序参数和Entity参数以外所有的参数必须是Component也就是必须继承IComponentData基类void Execute([EntityIndexInQuery]int sortKey, ref FallingCubeSpawner cubeValue)这种写法就代表无视第一个顺序参数筛选出所有挂载FallingCubeSpawner这个Component的Entity然后在方法中处理如果有一千个满足条件的Entity就会执行一千次如果只有一个那就只会执行一次参数可以无限往后叠加每增加一个参数就增加一个筛选条件void Execute([EntityIndexInQuery]int sortKey,ref LocalTransform localTransform,in FallCubeUsingValue cubeValue)同时这种写法还可以拥有一个参数类型为Entity工作流会自动将满足这些Component的Entity传入进来如果只需要操作数据参数则不需要获取实体void Execute([EntityIndexInQuery]int sortKey,Entity entity,ref LocalTransform localTransform,in FallCubeUsingValue cubeValue)同时参数中的Component前面需要有关键字ref 代表读写会读取并修改里面的值in 代表只读只会读取不会修改然后解释一下工作流上的标签[BurstCompile]意思是用 Burst 编译器编译这段代码机器码运行效率更快的编译更高效的编译器但是存在限制通过Burst编译的代码只能处理值类型数据以及将操作注册到ecb中不能调用引用类型的值比如stringclass不能调用Unity原生方法Debug.Log不能调用Unity原生对象(GameObject)Vector3在值类型中使用float3代替string在值类型中使用FixedString64Bytes代替使用方式完全相同还有FixedString32BytesFixedString128BytesFixedString512Bytes容纳更多字符按需使用[WithAll(typeof(CreatCubeTag))]额外增加一条筛选规则满足Execute参数筛选的同时额外拥有CreatCubeTag这个参数的Component的Entity才行这种通常只作为筛选条件不会用到里面的数据通常传入标签调用工作流(System中)顺序调用public partial struct FallingCubeSystem : ISystem { public void OnCreate(ref SystemState state) { state.RequireForUpdateFallingCubeSpawner(); } public void OnUpdate(ref SystemState state) { float deltaTime SystemAPI.Time.DeltaTime; EntityCommandBuffer ecb new EntityCommandBuffer(state.WorldUpdateAllocator); //这里开始是调用工作流 MoveCubeJob moveJob new MoveCubeJob(){deltaTime deltaTime,Ecb ecb.AsParallelWriter()}; ChangeAnimJob changeAnimJob new ChangeAnimJob() { deltaTime deltaTime }; state.Dependency moveJob.ScheduleParallel(state.Dependency); state.Dependency changeAnimJob.ScheduleParallel(state.Dependency); state.Dependency.Complete(); //在这里结束 ecb.Playback(state.EntityManager); ecb.Dispose(); } }先是创建工作流直接通过new进行实例化实例化的时候需要传入参数计算帧数的需要传入当前帧时间操作Entity的需要传入ecb对象state.Dependency IJobEntity.ScheduleParallel(state.Dependency);将实例化好的工作流添加到执行列表当中可以重复添加多个会按照添加的先后顺序执行state.Dependency.Complete();开始按照添加顺序执行工作流线程会开始等待直到工作流完成再执行后面的逻辑这样做性能非常好等工作流执行完成了再处理ecb中注册的Entity操作并行工作流public partial struct FallingCubeSystem : ISystem { public void OnCreate(ref SystemState state) { state.RequireForUpdateFallingCubeSpawner(); } public void OnUpdate(ref SystemState state) { float deltaTime SystemAPI.Time.DeltaTime; EntityCommandBuffer ecb new EntityCommandBuffer(state.WorldUpdateAllocator); //这里开始是调用工作流 MoveCubeJob moveJob new MoveCubeJob(){deltaTime deltaTime,Ecb ecb.AsParallelWriter()}; ChangeAnimJob changeAnimJob new ChangeAnimJob() { deltaTime deltaTime }; JobHandle moveHandle moveJob.ScheduleParallel(state.Dependency); JobHandle animHandle changeAnimJob.ScheduleParallel(state.Dependency); state.Dependency JobHandle.CombineDependencies(moveHandle, animHandle); //在这里结束 ecb.Playback(state.EntityManager); ecb.Dispose(); } }并行工作流在实例化工作流对象之后需要将工作流转化成JobHandle对象然后再将所有的JobHandle一起赋值给state.Dependency这种情况下多个工作流会一起执行没有先后顺序执行效率更高但是更容易出现ecb执行混乱出现先调用再注册的情况开发和调试难度要高于按顺序调用在工作流中改变能直接影响显示的属性1.LocalTransfrom[BurstCompile] [WithAll(typeof(FallingCubeTag))] public partial struct MoveCubeJob : IJobEntity { public float deltaTime; void Execute([EntityIndexInQuery]int sortKey,ref LocalTransform localTransform) { localTransform.Position.y - cubeValue.Value * deltaTime; } }LocalTransform必须带有ref修改LocalTransform中的值能够直接改变场景中Entity的位置2.改变Shader中字段的值首先需要在Component中进行一下特殊处理需要添加标签[MaterialProperty(_FrameIndex)] public struct ChangeShaderValue : IComponentData { public float Value; }其中这个标签尤其重要[MaterialProperty(_FrameIndex)]代表着这个Component被添加到Entity之后会自动寻找Entity上挂载的Renderer然后从Renderer上获取材质球然后找到材质球的Shader然后从Shader上寻找字符串中的字段也就是_FrameIndex这个字段意思是shader中必须存在_FrameIndex这个字段_FrameIndex(Frame Index, Float) 0同时在Component中必须有一个变量变量名必须为Value变量类型必须与Shader中的对应字段的类型一致public partial struct ChangeAnimJob : IJobEntity { public float deltaTime; void Execute(ref ChangeAnimValue animValue,ref ChangeShaderValue shaderValue) { animValue.index; if (animValue.index animValue.indexMax) { animValue.index 0; } shaderValue.Value animValue.index; } }然后直接在Job工具流中修改Value的值就能直接应用到材质球当中想要实时应用材质球必须使用MeshRenderer即使是2D也不能使用SpriteRenderer在2D中使用MeshRenderer来渲染2D图的时候MeshFilter的网格选择Quad待补充......Ecb实体处理器1.创建EntityEntity entity Ecb.Instantiate(sortKey,mainEntity);传入工作流顺序和需要创建的实体的原型返回创建出来的实体2.删除EntityEcb.DestroyEntity(sortKey,entity);传入工作流顺序和需要删除的实体删除传入的实体3.激活或隐藏EntityEcb.SetEnabled(sortKey, entity, true); Ecb.SetEnabled(sortKey, entity, false);传入工作流顺序和需要操作的实体然后最后传入是否激活true为激活false为隐藏4.为实体增加组件Ecb.AddComponentFallingCubeTag(sortKey,entity); Ecb.AddComponent(sortKey,entity,new FallCubeUsingValue{ Value 1.0f });用Ecb添加组件添加标签使用泛型添加数据需要实例化传入工作流顺序需要添加的实体以及泛型类型或实例化对象5.为实体的组件设置属性Ecb.SetComponent(sortKey, entity,LocalTransform.FromPosition(new float3(0, 20f, 0f)));用Ecb给已经添加的Component中的字段设置值这里是给刚创建的Entity设置初始位置也可以用另一种方式var t LocalTransform.FromPosition(new float3(randomX, 20f, 0f)); t.Scale 0.25f; Ecb.SetComponent(sortKey, cube, t);先根据位置创建出LocalTransfrom再给它的Scale赋值然后再传入SetComponent当中Ecs物理安装插件先在PackageManager安装Unity Physics然后再预制体中直接挂载Collider和RigBody就能直接在烘焙出来的Entity中使用物理了要注意必须使用3D物理即使是2D游戏也要使用3D物理使用2D物理没有效果处理物理碰撞的工作流创建物理工作流public partial struct TriggerJob : ITriggerEventsJob { public int sortKey; public ComponentLookupBulletTag bulletLook; public ComponentLookupFallingCubeTag cubeLook; public EntityCommandBuffer.ParallelWriter ecb; public void Execute(TriggerEvent triggerEvent) { Entity bulletEntity Entity.Null; Entity cubeEntity Entity.Null; bulletEntity bulletLook.HasComponent(triggerEvent.EntityA) ? triggerEvent.EntityA : bulletEntity; bulletEntity bulletLook.HasComponent(triggerEvent.EntityB) ? triggerEvent.EntityB : bulletEntity; cubeEntity cubeLook.HasComponent(triggerEvent.EntityA) ? triggerEvent.EntityA : cubeEntity; cubeEntity cubeLook.HasComponent(triggerEvent.EntityB) ? triggerEvent.EntityB : cubeEntity; if (bulletEntity ! Entity.Null cubeEntity ! Entity.Null) { ecb.DestroyEntity(sortKey, cubeEntity); } } }处理物理碰撞分为Trigger和Collision这里处理的是Trigger如果想要处理Collision的话工作流需要继承ICollisionEventsJob同时Execute方法的参数为CollisionEvent使用方式相同ComponentLookup 这个是物理工作流中必须要有的用来判断碰撞的两个物体是否拥有泛型中传入的这个标签继承了ITriggerEventsJob和ICollisionEventsJob的物理工作流里面的Execute方法会在任意两个拥有碰撞体且附带Triger和Rigbody的物体后执行并且出现持续碰撞的时候每帧都会执行无法在调用方法前筛选出要处理哪些碰撞所以必须要在方法内判断碰撞的两个物体是否是自己想要检测的物体判断就必须要通过ComponentLookup来判断triggerEvent.EntityA和triggerEvent.EntityB可以在方法中访问被碰撞的两个实体Entity然后调用ComponentLookup.HasComponent(Entity)方法在参数中传入想要判断的Entity可以判断这个实体中是否拥有创建时的泛型包含的组件用这种方式就可以判断出两个Entity是否为想要检测碰撞的两个物体然后处理逻辑调用工作流[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))] [UpdateAfter(typeof(PhysicsSimulationGroup))] public partial struct EcsPhysicsJobSystem : ISystem { public void OnCreate(ref SystemState state) { state.RequireForUpdateSimulationSingleton(); state.RequireForUpdateEndFixedStepSimulationEntityCommandBufferSystem.Singleton(); } public void OnUpdate(ref SystemState state) { var ecbSing SystemAPI.GetSingletonEndFixedStepSimulationEntityCommandBufferSystem.Singleton(); var ecb ecbSing.CreateCommandBuffer(state.WorldUnmanaged).AsParallelWriter(); TriggerJob triggerJob new TriggerJob { sortKey 0, bulletLook SystemAPI.GetComponentLookupBulletTag(), cubeLook SystemAPI.GetComponentLookupFallingCubeTag(), ecb ecb }; state.Dependency triggerJob.Schedule(SystemAPI.GetSingletonSimulationSingleton(), state.Dependency); } }先讲解两个标签[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]添加这个标签之后这个System会在FixedUpdate运算完成之后再进行运算如果没有添加这个标签就会在Update每帧渲染之后进行运算在Physics当中务必添加这个标签非Physics的System中不要添加[UpdateAfter(typeof(PhysicsSimulationGroup))]添加这个标签之后这个System会在物理碰撞模拟完成之后再运算System不添加这个标签的话可能会在物理运算完成之前执行System物理效果可能会出现错误或者延迟在Physics当中务必添加这个标签非Physics的System中不要添加var ecbSing SystemAPI.GetSingletonEndFixedStepSimulationEntityCommandBufferSystem.Singleton(); var ecb ecbSing.CreateCommandBuffer(state.WorldUnmanaged).AsParallelWriter();在调用物理工作流的System中Ecb不能直接用New实例化需要采用特定的方式进行创建SystemAPI.GetSingletonEndFixedStepSimulationEntityCommandBufferSystem.Singleton();这个方法会返回一个固定的Ecs原型通过这个方法返回的Ecs无法控制什么时候执行或者释放而是固定在每次FxedUpdate结束时的最后执行物理需要使用这种类型的Ecb不然会出现问题ecbSing.CreateCommandBuffer(state.WorldUnmanaged).AsParallelWriter()ecbSing.CreateCommandBuffer(state.WorldUnmanaged)这个方法会返回一个可用的Ecb然后通过.AsParallelWriter()返回一个可以在Job工作流中使用的Ecb实体SystemAPI.GetComponentLookupIComponentData()通过这个方法可以返回一个查找器这个查找器用来查找Entity中是否挂载着泛型中传入的Componentstate.Dependency triggerJob.Schedule(SystemAPI.GetSingletonSimulationSingleton(), state.Dependency)这句代码是真正的将Job添加到工作流.Schedule(SystemAPI.GetSingletonSimulationSingleton(), state.Dependency)这一段是固定的不需要修改任何参数只是前面的是自己实例化出来的Job就可以