概念
ECS即Entity Component System,实体组件系统。其中:
Entity:用于标识那些数据属于一个实体;
Component:存储数据(仅含数据,不含方法);
System:管理组件数据的更新(不同于传统的通过对象修改数据,这里通过System统一直接修改数据)
Unity版本:2019.3.3f1
CES依赖包:
“com.unity.collections”: “0.8.0-preview.5”,
“com.unity.entities”: “0.10.0-preview.6”,
“com.unity.jobs”: “0.2.9-preview.15”,
“com.unity.rendering.hybrid”: “0.5.0-preview.6”,
因为CES还在预览阶段,所以并不能保证本博客中的代码可以在其他版本中正常运行。
简单示例
该示例选自官方案例HelloCube 1.ForEach,首先创建一个含MeshFliter和MeshRender的GameObject,然后按照如下步骤:
1、创造Entity,只需要给GameObject添加转换脚本:
2、添加Component:给GameObject添加如下脚本:
using Unity.Entities;
// 这样这个脚本才能挂载到GameObject上
[GenerateAuthoringComponent]
public struct RotationSpeed_ForEach : IComponentData// 数据都是用结构体进行封装的
{
// 里面的数据不能含引用类型!
public float RadiansPerSecond;
}
3、添加System(System不用挂载到GameObject上):
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
public class RotationSpeedSystem_ForEach : SystemBase
{
protected override void OnUpdate()
{
float deltaTime = Time.DeltaTime;
// 通过组件筛选出实体实体
Entities
.WithName("RotationSpeedSystem_ForEach")
.ForEach((ref Rotation rotation, in RotationSpeed_ForEach rotationSpeed) =>
{
rotation.Value = math.mul(
math.normalize(rotation.Value),
quaternion.AxisAngle(math.up(), rotationSpeed.RadiansPerSecond * deltaTime));
})
.ScheduleParallel();
}
}
查看调试信息
查看调试信息:Window→Analysis→Entity Debugger