下一篇:Unity官方DOTS示例学习笔记(二) EntityComponentSystemSamples是官方现在还在维护的技术demo。可以用Unity2019.3.15或者Unity2020打开,不能用Unity2019.4.1打开。为什么我写了这三个Unity版本?因为这是今天(2020年6月27日)Unity hub上能直接下载的Unity2019以上的版本。 示例的github地址 https://github.com/Unity-Technologies/EntityComponentSystemSamples
EntityComponentSystemSamples/ECSSamples/Assets/HelloCube/1. ForEach/

1.Component:RotationSpeed_ForEach : IComponentData

只有一个成员,控制旋转的速度 [GenerateAuthoringComponent] public struct RotationSpeed_ForEach : IComponentData { public float RadiansPerSecond; } 注意属性[GenerateAuthoringComponent], 对于 IComponentData官方文档上这么解释这个属性的。 For IComponentData Unity can automatically generate authoring components for simple IComponentData components. When Unity generates an authoring component, you can add an IComponentData directly to a GameObject in a Scene within the Unity Editor. You can then use the Inspector window to set the initial values for the component. To indicate that you want to generate an authoring component, add the [GenerateAuthoringComponent] attribute to the IComponentData declaration. Unity automatically generates a MonoBehaviour class that contains the public fields of the component and provides a Conversion method that converts those fields over into runtime component data. 详见下面链接中For IComponentData一节的内容 https://docs.unity3d.com/Packages/com.unity.entities@0.11/manual/gp_overview.html
这一段是说For IComponentData作用。可以这么来理解:我们自己写的Component是一个继承IComponentData的struct(这里是RotationSpeed ForEach),是一个纯粹的数据结构定义,怎么和Entity产生联系? [GenerateAuthoringComponent]就是做这个的。Unity看到这个,就会帮我们自动生成一个MonoBehaviour的class,包含继承的IComponent的struct定义的public字段,和一个转换函数。这个写好了的Component是可以直接往prefab上拖,然后在inspector上直接修改RadiansPerSecond的值的。 ![](https://u3d-connect-cdn-public-prd.cdn.unity.cn/h1/20200627/p/images/d7448950-e7b1-4ad0-994e-6547c8c779e0__ .PNG)

2.System:RotationSpeedSystem_ForEach : SystemBase

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(); } }
这里OnUpdate可以简单理解为MonoBehavior的Update。每一帧都被调用。 (1)math.mul是新版的数学库函数,也是DOTS里用的数学库,是支持SIMD,在性能上会有大幅提升。有一点类似于shader语法里的运算。关于这个新版数学库,我更愿意称它为DOTS数学库。 (2)ForEach。。。。ScheduleParallel() 这是Job System的内容。 (3)内置Component。 RotationSpeed_ForEach是我们自己写的,这个Roation是什么呢?简单理解是DOTS内置的组件,也可以先理解成是Transform里的Rotation。打开它的定义,其实是一个IComponentData,且只有一个字段:一个四元数代表的旋转。当然这里的四元数quarternion是DOTS数学库的。
namespace Unity.Transforms { [Serializable] [WriteGroup(typeof(LocalToWorld))] [WriteGroup(typeof(LocalToParent))] [WriteGroup(typeof(CompositeRotation))] public struct Rotation : IComponentData { public quaternion Value; } }
Logo

分享前沿Unity技术干货和开发经验,精彩的Unity活动和社区相关信息

更多推荐