您现在的位置是:首页 > 文章详情

Unity之浅析 Entity Component System (ECS)

日期:2018-06-17点击:352

首先放出ECS官方文档

随着目前游戏对CPU性能要求的不断提升,单核高频的CPU对我们的帮助越来越有限。所以ECS(一种面向数据编程)多核心工作的方式也是大势所趋。

笔者对ECS的浅显理解就是

  • Entity 传统组件的集合,代替了GameObject的位置
  • Component 纯数据,不含有其他逻辑行为。;例如:旋转速度,缩放大小之类的
  • System 业务逻辑,根据组件的集合(Enitites)和纯数据(Components)编写对应的逻辑

下面是环境配置,笔者使用的版本为Unity 2018.2.0b8 (64-bit)

目前的ECS分为两种 Pure ECS 与 HyBridECS 区别主要就是Pure版的不能使用GameObjectsMonoBehaviours 下面的示例用的是Hybrid版本

工程文件下载

下载安装后把.Net版本换成4.6

img_1ce3fe67efff5d821f15d34df3ab3197.png
然后安装对应的Packages包,这是一个unity的新功能,以后安装插件会更容易管理
img_3c56aecdfa570bc6518635ee2f3ae060.png

拖拽出对应的Entity Debugge面板

img_2487c620e4bb1daddf9dd5e01ebaaeb0.png

在两个对应的模型上添加两个脚本 GameObjectEntity(Unity自带脚本,没有这个ECS系统是不会执行的,相当于向ECS中注册)与RotationPlanet(稍后讲解)

这是会在Debugge面板上看到两个物体对应的Entity

img_c60ee0a268385cb10e6188c87fc30252.png

接下来是业务执行脚本 RotationPlanetSystem

img_8fc4cf44e5906548483b3fbedb7c7c32.png

运行

img_8f86a389e4fda125a1e2dfaa4a6dfda5.png
img_c9937234a404e550a51faa3ae2009bba.gif

多数据操作(ComponentArray)

效果如下:

img_c6b42bd266fac9f52c04f7986caf0a37.gif

纯数据

using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 纯数据 /// </summary> public class InputComponent : MonoBehaviour { public float horizontal; public float vertical; } 

控制所有星球的移动

using System.Collections; using System.Collections.Generic; using UnityEngine; using Unity.Entities; //根据指定的数值对星球进行移动控制 public class PlanetMovementSystem : ComponentSystem { /// <summary> /// Entity 组件集合 /// </summary> private struct component { public Rigidbody rigidbody; public InputComponent inputComponent; } /// <summary> /// 具体逻辑操作 /// </summary> protected override void OnUpdate() { var deltaTime = Time.deltaTime; foreach (var entity in GetEntities<component>())//获取所有指定的Entity { var moveVector = new Vector3(entity.inputComponent.horizontal, 0, entity.inputComponent.vertical); var movePosition = entity.rigidbody.position + moveVector.normalized * 6 * deltaTime; entity.rigidbody.MovePosition(movePosition); } } } 

控制所有纯数据的数值更改

其中Inject特性在ECS features in detail中有讲解

using System.Collections; using System.Collections.Generic; using UnityEngine; using Unity.Entities; public class InputSystem : ComponentSystem { private struct Data { public int Length; public ComponentArray<InputComponent> inputComponents; //数据集合 } /// <summary> /// Inject特性在unity启动时自动赋值合适的Value /// </summary> [Inject] private Data data; protected override void OnUpdate() { var horizontal = Input.GetAxis("Horizontal"); var vertical = Input.GetAxis("Vertical"); for (int i = 0; i < data.inputComponents.Length; i++) { data.inputComponents[i].horizontal = horizontal; data.inputComponents[i].vertical = vertical; } } } 
原文链接:https://yq.aliyun.com/articles/666173
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章