本章节为大家解析ECS案例,资源来自,大家自行获取:
https://github.com/Unity-Technologies/EntityComponentSystemSamples
ECS案例解析
1、ForEach——ECS入门案例
在该案例中有两个组件,一个是RotationSpeedSystem_ForEach,还有一个是ConvertToEntity
1.1、ConvertToEntity——Entity
这个组件的作用就是:将Inspector面板的GameObject从根节点开始,将整个GameObject(包括子物体)全部转成Entity,并且将所有现有的、能转化的Component转换成ECS的Component
在ConvertToEntity代码中,执行了GameObjectConversionUtility.Convert()函数,而"能转化"的四亿是只有当该组件实现了接口IConvertGameObjectToEntity的Convert()函数,才会根据Convert()函数产生作用
最后把原本的GameObject销毁掉
1.2、RotationSpeedAuthoring_ForEach——Convert
using System;
using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;
[RequiresEntityConversion]
public class RotationSpeedAuthoring_ForEach : MonoBehaviour, IConvertGameObjectToEntity
{
public float DegreesPerSecond;
//那么这里就是实现了1.1中的Convert函数,在这个Convert函数中
//将MonoBehaviour的参数作为RotationSpeed_ForEach组件的参数传入
//并且从角度制变为弧度制
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
var data = new RotationSpeed_ForEach {
RadiansPerSecond = math.radians(DegreesPerSecond) };
dstManager.AddComponentData(entity, data);
}
}
1.3、RotationSpeed_ForEach——Component
ECS中的组件继承IComponentData,是struct类型,而在这个结构体中只保存了数据
using System;
using Unity.Entities;
// Serializable属性是为了支持编辑器
[Serializable]
//记住IComponentData是struct类型
public struct RotationSpeed_ForEach : IComponentData//首先要继承IComponentData
{