Unity ECS 入门

本文主要总结Hybrid ECS基础用法,Pure ECS将会在之后进行补充。不详细描述ECS概念与原理。更多内容推荐一个博客 笨木头与游戏开发 Unity ECS 入门 。他总结得很详细,故不赘述。

1. 新手入门

我的学习顺序:

2. HelloCube 总结

本文总结了 HelloCube 里ECS的基础用法。HelloCube项目中使用的是Hybrid ECS,混合了Unity原来的GameObject-Component-MonoBehaviour的使用方式。Pure ECS则更为纯粹,只需要关注ECS本身无需GameObject转化。

必须安装的两个Packages

HelloCube

下表总结每个Sample的主要内容:

Sample 主要内容
1.ForEach 实现Entity:数据和功能的分离、遍历实体
2.IJobChunk 实现Entity:直接访问块
3.SubScene
4. SpawnFromMonoBehaviour 使用Prefab生成Entity:从MonoBehaviour中
5. SpawnFromEntity 使用Prefab生成Entity:从Job中
6. SpawnAndRemove 销毁Entity:从Job中

对ECS的一些理解:

  • 一个 组件Component可以储存 很多不同 的数据Data。
  • 一个 实体Entity利用索引的方式可以管理 很多不同 组件的访问,但不实现任何功能。
  • 一个 系统System则利用遍历、筛选的方式去实现了 很多同一类型 的实体的功能。
ECS 相关脚本
Entity ConvertToEntity
Component IComponentData
System JobComponentSystem

从Samples中可以总结以下几种实现:

方式
实现Component IComponentData
实现Entity Authoring Attribute、Authoring Interface
实现System Foreach、JobForEach、JobChunk
在Job中生成/销毁Entity EntityCommandBufferSystem

3. 实现Component

只有一种方式,就是实现接口IComponentData。

public struct RotationSpeed_ForEach : IComponentData
{
    public float RadiansPerSecond;
}

4. 实现Entity

事实上实现Entity需要两个关键点:

  • ConvertToEntity:ConvertToEntity是Entities库里自带的脚本,添加它到一个GameObject上。
  • Authoring Script: 有两种实现方式,我把它们分为 Authoring Attribute 和 Authoring Interface。下文会介绍他们。同样的需要把Authoring Script添加到同一个GameObject上。
GameObject Inspector

4.1 Authoring Attribute

之所以叫它Authoring Attribute, 是因为它利用了一个Attribute [GenerateAuthoringComponent]实现Authoring Script。

[GenerateAuthoringComponent]
public struct RotationSpeed_ForEach : IComponentData
{
    public float RadiansPerSecond;
}

然后可以直接将这个ECS中的Component脚本作为Authoring Script添加到GameObject中。


GameObject Inspector

4.2 Authoring Interface

同样的,叫它Authoring Interface的理由是它利用接口IConvertGameObjectToEntity实现了Authoring Script。实现IConvertGameObjectToEntity的关键是实现Convert(),把Component添加到Entity中。EntityManager 一个重要功能是给Entity添加component :entityManager.AddComponentData(entity, componnet);

[Serializable]
public struct RotationSpeed_IJobChunk : IComponentData
{
    public float RadiansPerSecond;
}

public class RotationSpeedAuthoring_IJobChunk : MonoBehaviour, IConvertGameObjectToEntity
{
    ...
    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        var data = new RotationSpeed_IJobChunk { ... };
        dstManager.AddComponentData(entity, data);
    }
}

然后将这个Authoring脚本添加到GameObject中。注意到现在的Component因为没有使用[GenerateAuthoringComponent]已经无法再作为Authoring脚本了。

GameObject Inspector

简单回顾一下实现Entity的过程:

  • 利用ConvertToEntity脚本,将GameObject转化为Entity。
  • 实现Component。
  • 实现Authoring脚本,并将Component添加到Entity中。

5. 实现System

有三种方法实现System功能:Foreach、JobForEach、JobChunk。

5.1 ForEach

ForEach有两个关键点:

  • 重载JobComponentSystem.OnUpdate()实现System功能。
  • 使用JobComponentSystem.Entities.ForEach()遍历所有Entity。
//JobComponentSystem脚本不需要添加到GameObject中就可以执行
public class RotationSpeedSystem_ForEach : JobComponentSystem
{
    protected override JobHandle OnUpdate(JobHandle inputDependencies)
    {
        ...
        var jobHandle = Entities
            .WithName("RotationSpeedSystem_ForEach")
            //JobComponentSystem会利用ForEach参数进行筛选,带有这些参数才会执行对应
            .ForEach((ref Rotation rotation, in RotationSpeed_ForEach rotationSpeed) =>
             {
                //Implement function for entity
             })
            .Schedule(inputDependencies);
        return jobHandle;
    }
}

5.2 JobForEach

和ForEach方法的区别是,不需要使用JobComponentSystem.Entities.ForEach()而是实现IJobForEach。IJobForEach一样会自动遍历筛选Entities,两者效果一致。

public class RotationSpeedSystem_ForEach : JobComponentSystem
{
    [BurstCompile]
    struct RotateJob : IJobForEach<Rotation,RotationSpeed_ForEach>
    {
        ...
        public void Execute(ref Rotation rotation, ref RotationSpeed_ForEach rotationSpeed)
        {
            //Implement function for entity
        }
    }

    protected override JobHandle OnUpdate(JobHandle inputDependencies)
    {
        var jobHandle = new RotateJob { ... }.Schedule(this,inputDependencies);
        return jobHandle;
    }
}

5.3 JobChunk

前面的两种方法ForEach、JobForEach都是去遍历相应实体,而JobChunk是在Job中遍历 块Chunk。HelloCube项目描述 JobChunk 更为灵活,可以处理更复杂的情况,并且保持最高效率。从推荐来排名:JobChunk > JobForEach > ForEach。

public class RotationSpeedSystem_IJobChunk : JobComponentSystem
{
    EntityQuery m_Group;

    protected override void OnCreate()
    {
        m_Group = GetEntityQuery(typeof(Rotation), ComponentType.ReadOnly<RotationSpeed_IJobChunk>());
    }

    [BurstCompile]
    struct RotationSpeedJob : IJobChunk
    {      
        public ArchetypeChunkComponentType<Rotation> RotationType;
        [ReadOnly] public ArchetypeChunkComponentType<RotationSpeed_IJobChunk> RotationSpeedType;

        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            var chunkRotations = chunk.GetNativeArray(RotationType);
            var chunkRotationSpeeds = chunk.GetNativeArray(RotationSpeedType);
            for (var i = 0; i < chunk.Count; i++)
            {
                var rotation = chunkRotations[i];
                var rotationSpeed = chunkRotationSpeeds[i];

                //Do something
            }
        }
    }

    protected override JobHandle OnUpdate(JobHandle inputDependencies)
    {  
        ...
        var rotationType = GetArchetypeChunkComponentType<Rotation>();
        var rotationSpeedType = GetArchetypeChunkComponentType<RotationSpeed_IJobChunk>(true);
        var job = new RotationSpeedJob(){...};
        return job.Schedule(m_Group, inputDependencies);
    }
}

关键就在于IJobChunk的Execute()方法里,同样是需要对Entities进行遍历筛选:

  • 筛选:拥有完全相同Components的Entities都会放在同一个ArchetypeChunk中,这一步就已经完成了筛选。
  • 遍历:遍历ArchetypeChunk,即for (var i = 0; i < chunk.Count; i++),同样的索引即是同一个Entity。注意应提前使用GetNativeArray(Type)来取出同一组Component以提高效率。

这里更能直接体现面向数据的思想,数据整齐地分布在一组组Chunk,“对象”概念被替换为作为实体Entity概念,在chunk中利用索引去获取实体的数据。事实上性能提升的关键就是,用索引去获取整齐分布的数据。在很多项目中,利用这一点去提升性能即可,是不是ECS并不重要。

6. 使用Prefab生成Entity

上文中,实现了Component、Entity、System的GameObject可以存为一个Prefab,并且可以动态地实例化这个Prefab。

一个重要前提:GameObject Prefab不能直接初始化成Entity。需要先把Prefab转化为Entity Prefab才能使用。

利用Prefab生成Entity的方法有两种:

  • From MonoBehaviour
  • From Entity

6.1 From MonoBehaviour

两个关键步骤:

  • GameObject Prefab 转化为 Entity Prefab:var entity_prefab = ConvertGameObjectHierarchy(gameObject_prefab, settings);
  • 实例化 Entity Prefab:entityManager.Instantiate(entity_prefab);
    public GameObject Prefab;

    void Start()
    {
        var settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, null);
        var prefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(Prefab, settings);
        var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
        ...
        var instance = entityManager.Instantiate(prefab); 
        var position = transform.TransformPoint();
        entityManager.SetComponentData(instance, new Translation {Value = position});
    }

6.2 From Entity

实际上,就是使用Prefab从Job中生成Entity。

一个重要前提:Unity ECS 为了防止条件竞争,不能直接在Job中创建/销毁Entity。为了解决这个问题,需要使用EntityCommandBufferSystem。

两个关键步骤:

  1. Spwaner Component、Spwaner Entity
    用一个Spwaner entity来存储Entity Prefab,并在对应的Authoring脚本中转化GameObject Prefab。注意:IDeclareReferencedPrefabs是必需的部分,否则conversionSystem.GetPrimaryEntity(gameObjcet_prefab)无法使用。
public struct Spawner_FromEntity : IComponentData
{
    public Entity Prefab;
}

public class SpawnerAuthoring_FromEntity : MonoBehaviour, IDeclareReferencedPrefabs, IConvertGameObjectToEntity
{
    public GameObject Prefab;

    public void DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
    {
        referencedPrefabs.Add(Prefab);
    }

    public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
    {
        var spawnerData = new Spawner_FromEntity
        {          
            Prefab = conversionSystem.GetPrimaryEntity(Prefab),
        };
        dstManager.AddComponentData(entity, spawnerData);
    }
}
  1. Spwaner System
    在JobComponentSystem中使用EntityCommandBufferSystem实例化Entity Prefab。
[UpdateInGroup(typeof(SimulationSystemGroup))]
public class SpawnerSystem_FromEntity : JobComponentSystem
{
    BeginInitializationEntityCommandBufferSystem m_EntityCommandBufferSystem;

    protected override void OnCreate()
    {
        m_EntityCommandBufferSystem = World.GetOrCreateSystem<BeginInitializationEntityCommandBufferSystem>();
    }

    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        var commandBuffer = m_EntityCommandBufferSystem.CreateCommandBuffer().ToConcurrent();

        var jobHandle = Entities
            .WithName("SpawnerSystem_FromEntity")
            .WithBurst(FloatMode.Default, FloatPrecision.Standard, true)
            .ForEach((Entity entity, int entityInQueryIndex, in Spawner_FromEntity spawnerFromEntity, in LocalToWorld location) =>
        {
               ...
               var instance = commandBuffer.Instantiate(entityInQueryIndex, spawnerFromEntity.Prefab);
               ...
               commandBuffer.SetComponent(entityInQueryIndex, instance, new Translation {Value = position});
               ...
            }
            commandBuffer.DestroyEntity(entityInQueryIndex, entity);
        }).Schedule(inputDeps);
        m_EntityCommandBufferSystem.AddJobHandleForProducer(jobHandle);
        return jobHandle;
    }
}

注意:

  • EntityCommandBuffer会在下一帧被EntityCommandBufferSystem使用,所以有一帧延迟。
  • var instance = commandBuffer.Instantiate(entityInQueryIndex, spawnerFromEntity.Prefab);
    这里利用commandBuffer来实例化Prefab,commandBuffer代替了EntityManager的功能entityManager.Instantiate(prefab);
  • commandBuffer.DestroyEntity(entityInQueryIndex, entity);
    下一帧不需要重复使用Spwaner Entity生成Prefab Entity,所以就销毁了Spwaner Entity避免重复生成。

小结:

  • 如果想在MonoBehaviour生成Prefab Entity就使用EntityManager实例化。
  • 如果想在job中生成Prefab Entity就需要使用EntityCommandBuffer,一种做法是给创建Prefab这个过程做成一个Spwaner Entity,并且用一次就销毁。
  • 在job中,commandBuffer完成了原本EntityManager的功能。

7. 在Job中生成/销毁Entity

上文中已经知道了为了避免条件竞争,无法直接在Job生成/销毁Entity,必须使用EntityCommandBuffer。而EntityCommandBuffer也分为多种。

名称 功能
BeginInitialization EntityCommandBufferSystem 生成
EndSimulation EntityCommandBufferSystem 销毁

它们的区别在于执行顺序。

public class LifeTimeSystem : JobComponentSystem
{
    EntityCommandBufferSystem m_Barrier;

    protected override void OnCreate()
    {
        m_Barrier = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();
    }

    [BurstCompile]
    struct LifeTimeJob : IJobForEachWithEntity<LifeTime>
    {
        ...
        [WriteOnly]
        public EntityCommandBuffer.Concurrent CommandBuffer;

        public void Execute(Entity entity, int jobIndex, ref LifeTime lifeTime)
        {
             ...
            CommandBuffer.DestroyEntity(jobIndex, entity);
        }
    }

 protected override JobHandle OnUpdate(JobHandle inputDependencies)
    {
        var commandBuffer = m_Barrier.CreateCommandBuffer().ToConcurrent();
        var job = new LifeTimeJob {..., CommandBuffer = commandBuffer}.Schedule(this, inputDependencies);        
        m_Barrier.AddJobHandleForProducer(job);
        return job;
    }

8. 一个简单的练习

到现在为止最基础的 Unity ECS 用法已经足够了。有了这个基础进阶代码都可以看懂跟着写。做一个简单的总结性练习,回顾如何使用上文的那些基础用法。

GameObject转化为Entity:Authoring Attribute、Authoring Interface
System实现Entity旋转: ForEach、JobForEach、JobChunk
生成/销毁Prefab:From MonoBehavior、From Job

SampleScene1: Authoring Attribute + ForEach + From MonoBehaviour
SampleScene2: Authoring Interface + JobForEach + From Entity (Better)
SampleScene3: Authoring Interface + JobChunk + From Entity(Best)

代码托管:LearningECS

9. 下一篇

下一篇会介绍Pure ECS的用法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354

推荐阅读更多精彩内容