参考:Unity中文课堂刘国栋老师的《Unity ECS(一)轻松入门》
Unity公司在2018年逐渐加大ECS技术的推广力度。
2017年守望先锋最早采用的游戏框架,极大提高游戏运行的效率。ECS的性能强悍,能够在同一个场景中展示海量的游戏对象。基于unity引擎所开发出来的游戏、vr、ar产品运行效率会有极大的提高。
ECS三要素
组件、系统、管理器
在2018环境下的ECS环境配置
学习ECS项目,需要导入5个包
- Entities
- Mathematics 数学
- Hybrid Render 混合渲染
- Jobs
- Burst
简单的ECS项目只需要安装前三个插件(我使用的是2018.4.34f1)
18版本HelloWorld
让一个cube在场景中旋转起来。
在场景中制作一个红色的Cube,并为它添加组件和系统两个脚本。RotationCubeComponent.cs和RotationCubeSystem.cs
RotationCubeComponent.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class RotationCubeComponent : MonoBehaviour
{public float speed;
}
RotationCubeSystem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
public class RotationCubeSystem : ComponentSystem
{struct Group{public RotationCubeComponent rotation;public Transform transform;}protected override void OnUpdate(){foreach (var en in GetEntities<Group>()){en.transform.Rotate(Vector3.down, en.rotation.speed * Time.deltaTime);}}
}
RotationCubeComponent.cs继承MonoBehaviour可以直接拖拽到Cube上&#xff0c;但是系统无法添加到cube上。
此时需要添加Entities系统脚本Game Object Entity&#xff0c;可以把这个脚本当作管理脚本&#xff0c;把组件和系统关联起脸&#xff0c;放Cube可以运行起来。
在这个HelloWorld里&#xff0c;创建了两个脚本
- RotationCubeComponent.cs
继承MonnoBehaviour&#xff0c;内部定义Cube的旋转速度。 - RotationCubeSystem.cs
继承ComponetSystem&#xff0c;定义Group的结构体&#xff0c;然后再OnUpdate()中使用foreach循环让Cube旋转。 - GameObjectEntity.cs
属于Entitys命名空间中的内置脚本&#xff0c;作用是吧“组件”和“系统”结合起来
通过Demo回看ECS
下图是Unity官方的关于ECS的整体架构核心示意图。
在开发的时候先开发组件&#xff0c;然后再开发一个系统&#xff0c;组件相当于把OOP编程当中一个类的变量们放在一起&#xff0c;系统则是把类中的方法放在一起。
ECS中实体与组件的关系是一个Entity可以包含多个组件&#xff0c;即一个实体可以包含多个组件&#xff0c;在上面的代码中定义了Struct Group不仅包含了自定义的rotation还有系统自带的transform组件。
实体管理器是有系统GameObjectEntity来代替的&#xff0c;结合定义的系统和组件。在2019版本中不是系统脚本代替&#xff0c;而是自己来写管理器脚本。
Entities与MonoBehaviour之间的对比
- Entity是一个实体相当于OOP编程中的GameObject
- 实体中的组件相当于传统继承MonoBehaviour组件中的字段变量
- 系统则相当于Update方法