sunagimoブログ

主にUnityに関する技術を取り上げます

【Unity】ECS(Entity Component System)を使ってみる

ECSとは

C#JobSystemと同様に、CPUを極限まで使う、
新しいアーキテクチャパターン


ECSの要素

Entity

GameObjectに変わるもの

Component Data

Entityに格納するデータ

Component System

処理部分

Component Group

ComponentDataの種類を設定


ECSの動作
Component SystemとComponent Dataは別々に実装
Entity内に複数のComponent Dataが格納される
Component DataがComponent Groupの要求するデータ設定を満たしていれば、
Component Systemが呼ばれる


サンプル
Updateで数値をカウントさせて、ラベルに反映させる

MonoBehaviour

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using TMPro;

public class EntityMain : MonoBehaviour
{
    [SerializeField]
    TextMeshProUGUI textLbl;

    EntityManager manager;
    Entity entity;

    void Start()
    {
        manager = World.Active.GetOrCreateManager<EntityManager>();
        var archeType = manager.CreateArchetype(typeof(CountData));
        entity = manager.CreateEntity(archeType);
    }
    
    void Update()
    {
        textLbl.text = manager.GetComponentData<CountData>(entity).Count.ToString();
    }
}



ComponentData

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using System;

[Serializable]
public struct CountData : IComponentData
{
    public int Count;
}



ComponentSystem、ComponentGroup

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using TMPro;

public class EntityCountSystem : ComponentSystem
{
    struct Group
    {
        public readonly int Length;
        public ComponentDataArray<CountData> countData;
    }

    [Inject]
    Group group;

    protected override void OnUpdate()
    {
        for(var idx = 0; idx < group.Length; ++idx)
        {
            var countData = group.countData[idx];
            countData.Count++;
            group.countData[idx] = countData;
        }
    }
}



まとめ

ECS、JobSystem、BurstCompilerを組み合わせることで
より効果が発揮されると思います。
今までの実装方法と大きく変わっているので、学習時間は必要ですが
今後もTinyModeのように必須の機能となっていくかもしれません


参考にさせていただいたサイト様

tsubakit1.hateblo.jp

qiita.com