0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

自分用Unity ECS辞書 Unity 6.6版

0
Posted at

自分用Unity ECS辞書 Unity 6.6版

ECSを勉強して新たに知ったことや、バージョンが新しくなったことで変わったものがあるので再度書いてみた。

基本形

using Unity.Burst;
using Unity.Entities;
using Unity.Transforms;

public struct MoveSpeed : IComponentData
{
    public float Value;
}

public partial struct MoveSystem : ISystem
{
    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        float deltaTime = SystemAPI.Time.DeltaTime;

        foreach (var (transform, speed) in
                 SystemAPI.Query<
                     RefRW<LocalTransform>,
                     RefRO<MoveSpeed>>())
        {
            transform.ValueRW.Position.x += speed.ValueRO.Value * deltaTime;
        }
    }
}

データを IComponentData として定義し、ISystem が条件に合うEntityを見つけて処理する。

Unity ECSでは、従来のように1つのMonoBehaviourにデータと処理を書くのではなく、EntityにComponentというデータを付け、そのComponentを持つEntityをSystemがまとめて処理する。

Unity 6.4以降、Unity.Entities を含む主要ECSパッケージはエンジン標準のCore Packageとなり、バージョン番号もUnity本体に合わせて 6.6 のように同期するようになった。

以下の情報は古いものとしてくれ。

  • 検索と反復処理: Entities.ForEach と IAspect は非推奨。メインスレッドのループなら SystemAPI.Query、並列処理なら IJobEntity を使う。
  • データの持ち方: Unity 6.6から、class で定義するManaged Component(および AddComponentObject / GetComponentObject 系API)と、マネージドフィールドを含む ISharedComponentData が非推奨となった。PrefabやMaterialなどの UnityEngine.Object を参照したい場合は、struct のComponent内に UnityObjectRef<T> を持たせる。
  • エディタ確認: 従来の専用Entities Hierarchyウィンドウは廃止され、Unity 6.6からは標準のHierarchyウィンドウ上でGameObjectとEntityを一緒に確認・検索する形に統合されている。

索引

基本

用語 説明
Entity ECS世界のGameObject。
EntityId GameObjectとEntityで共通化された64bit識別子。
IComponentData Entityに付けるデータ。struct で作る。
UnityObjectRef<T> UnmanagedなComponentからUnityオブジェクトを参照する型。
Tag Component フィールドを持たない目印用Component。
ISystem Componentを読み書きする処理を書く場所。
SystemAPI.Query 条件に合うEntityのComponentを列挙する。
RefRO<T> / RefRW<T> Componentを読み取り専用、または読み書き可能として扱う。
LocalTransform ECS側の位置、回転、スケールを扱うComponent。

Authoring・Baking系

用語 説明
Authoring Inspectorから値を設定するためのMonoBehaviour。
Baker<T> Authoringの値をEntityのComponentへ変換する。
GetEntity Baker内でGameObjectに対応するEntityを取得する。
TransformUsageFlags EntityにどのTransform系Componentを持たせるかを指定する。
SubScene ECS用にBakeされるScene単位。

Entity操作系

用語 説明
EntityManager EntityやComponentを直接操作する。
EntityCommandBuffer Entityの生成・破棄・Component追加などを後でまとめて実行する。
Instantiate Entity PrefabからEntityを複製する。
DestroyEntity Entityを破棄する。
AddComponent / RemoveComponent / SetComponent EntityのComponent構成を変更したり、値を更新したりする。

検索・状態系

用語 説明
RequireForUpdate 指定Componentが存在するときだけSystemを動かす。
Singleton World内に1つだけ存在するComponentを取得する。
DynamicBuffer<T> Entityに可変長の配列的データを持たせる。
IEnableableComponent Componentを付け外しせずに有効・無効を切り替える。
EntityQuery 条件に合うEntity群を表す検索条件。
ComponentLookup<T> 指定したEntityから特定のComponentを直接引く。

メモリ・共有データ系

用語 説明
BlobAsset / BlobAssetReference<T> 複数のEntityで共有できる読み取り専用の不変データ。
ISharedComponentData 同じArchetype内で、共有値ごとにEntityをChunk単位で分類するComponent。
ICleanupComponentData Entity破棄時に後始末が終わるまで消去を保留するComponent。

Unity Physics・衝突イベント系

用語 説明
PhysicsVelocity / PhysicsMass 物理移動の速度と質量プロパティを扱うComponent。
PhysicsWorldSingleton レイキャストや空間クエリを行うための物理ワールドの入口。
SimulationSingleton 衝突イベントやトリガーイベントのJobをスケジュールする入口。
ICollisionEventsJob Collisionを処理するための専用Job。
ITriggerEventsJob Triggerを処理するための専用Job。

デバッグ系

用語 説明
IDebugOnAdded / IDebugOnRemoved Componentの追加・削除時に発火するデバッグ用コールバック。

Job・Burst・実行順系

用語 説明
IJobEntity Componentの処理をJobとして書く。
BurstCompile Burstコンパイル対象にする属性。
UpdateInGroup / UpdateBefore / UpdateAfter Systemが実行されるグループと順序を指定する。

Entity

ECS世界の対象そのもの。

Entity entity = state.EntityManager.CreateEntity();

Entity はデータを持たず、ただの識別ID。位置、速度、HP、敵フラグなどはEntityに付いているComponentで決まる。

state.EntityManager.AddComponentData(entity, new MoveSpeed
{
    Value = 5f
});

EntityId

Unity 6.4〜6.6にかけて導入・移行が進められた、GameObjectとECSのEntityを統一的に扱うための64bit識別子。

EntityId id = gameObject.GetEntityId();

従来のUnityでは GetInstanceID() が32bitの int を返していたが、GetInstanceID() は非推奨となり、64bitの EntityId に置き換わった。

EntityId を int にキャストしたり、正負の符号でアセットかどうかを判定したりする古い書き方は動かないため、純粋な識別子型としてそのまま扱う必要がある。

IComponentData

Entityに付けるデータ。struct で定義する。

using Unity.Entities;

public struct Health : IComponentData
{
    public float Current;
    public float Max;
}

Componentにはメソッドを書かず、値だけを持たせるのが基本になる。

過去のバージョンでは class で IComponentData を実装するManaged Componentも使われていたが、Unity 6.6でManaged Componentは非推奨となった。これから書くコードでは、IComponentData はすべてUnmanagedな struct として定義する。

UnityObjectRef<T>

Unmanagedな struct のComponent内に、GameObject、Material、Mesh、ScriptableObject などの UnityEngine.Object 参照を保持するためのラッパー構造体。

using Unity.Entities;
using UnityEngine;

public struct CharacterViewConfig : IComponentData
{
    public UnityObjectRef<Material> HitMaterial;
    public UnityObjectRef<ScriptableObject> AiProfile;
}

Unity 6.6で class ベースのManaged Componentや AddComponentObject / GetComponentObject が非推奨になったため、Unityオブジェクトへの参照を持たせたい場合はこの UnityObjectRef<T> を使う。

中身自体はUnmanagedな構造体として扱われるため、Chunkのメモリレイアウトを壊さず、通常の AddComponentData や SystemAPI.Query でそのまま扱える。なお、List<T> や HashSet<T> のようなマネージドコレクションをどうしても持たせたい場合は、データを ScriptableObject に逃がしたうえで UnityObjectRef<T> で参照する形をとる。

Tag Component

フィールドを1つも持たない IComponentData。Entityの種類や状態を見分けるタグとして使う。

using Unity.Entities;

public struct EnemyTag : IComponentData { }
public struct PlayerTag : IComponentData { }

メモリ上のサイズを消費せず、検索条件として高速に機能する。「敵だけに処理を走らせたい」「プレイヤーのEntityだけを特定したい」という場面で付ける。

ISystem

Componentを読み書きする処理を書く場所。partial struct で定義する。

using Unity.Burst;
using Unity.Entities;

public partial struct HealSystem : ISystem
{
    // public void OnCreate(ref SystemState state) { } // 省略可

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        // 毎フレームの処理
    }

    // public void OnDestroy(ref SystemState state) { } // 省略可
}

MonoBehaviourの Start / Update / OnDestroy に相当するのが OnCreate / OnUpdate / OnDestroy だ。

クラスベースの SystemBase も残ってはいるが、Burstコンパイルの対象にはできない。

SystemAPI.Query

ISystem の OnUpdate 内で、条件に合うEntityのComponentを順番に取り出すためのAPI。

float deltaTime = SystemAPI.Time.DeltaTime;

foreach (var (transform, speed) in
         SystemAPI.Query<
             RefRW<LocalTransform>,
             RefRO<MoveSpeed>>()
         .WithAll<EnemyTag>())
{
    transform.ValueRW.Position.z -= speed.ValueRO.Value * deltaTime;
}

Source Generatorによってコンパイル時に最適化されたクエリコードへ展開される。後ろに .WithAll<T>()(指定Componentを持つ)、.WithNone<T>()(指定Componentを持たない)、.WithAny<T>() などを繋げて対象を絞り込める。

ループの最後に対象の Entity 自体も受け取りたい場合は、タプルの末尾に .WithEntityAccess() を付ける。

foreach (var (health, entity) in
         SystemAPI.Query<RefRO<Health>>()
         .WithEntityAccess())
{
    if (health.ValueRO.Current <= 0f)
    {
        // entity を使った処理
    }
}

RefRO<T> / RefRW<T>

SystemAPI.Query などでComponentを受け取るときに、読み取り専用か読み書き可能かを明示するラッパー。

foreach (var (transform, speed) in
         SystemAPI.Query<
             RefRW<LocalTransform>,
             RefRO<MoveSpeed>>())
{
    // 書き換える側は ValueRW、読むだけの側は ValueRO
    transform.ValueRW.Position.x += speed.ValueRO.Value;
}

ECSでは、どのSystemがどのComponentを書き換えるかによってJobの依存関係や変更検知が決まる。書き換えないComponentをすべて RefRO<T> にしておくと、不要な書き込みロックや変更フラグの更新を防げる。

LocalTransform

ECS側で位置(Position)、回転(Rotation)、均一スケール(Scale)を保持する基本Component。Unity.Transforms 名前空間にある。

using Unity.Mathematics;
using Unity.Transforms;

// 位置・回転・スケールを指定して生成
LocalTransform newTransform = LocalTransform.FromPositionRotationScale(
    new float3(0f, 1f, 0f),
    quaternion.identity,
    1f
);

// 平行移動や回転のヘルパーも用意されている
newTransform = newTransform.Translate(new float3(1f, 0f, 0f));

GameObjectの Transform と違い、ECSの LocalTransform は単なる構造体データだ。親子関係がある場合は Parent Componentと組み合わさり、Transforms Systemが最終的なワールド行列である LocalToWorld を計算して描画系へ渡す。


Authoring

UnityエディタのInspectorから値を設定するための、通常の MonoBehaviour クラス。

using UnityEngine;

public sealed class MoveSpeedAuthoring : MonoBehaviour
{
    [SerializeField] private float _speed = 5f;
}

ECSの IComponentData はそのままではGameObjectにアタッチできないため、編集用の窓口として MonoBehaviour を用意する。これをAuthoring Componentと呼ぶ。実行時にはこの MonoBehaviour 自体が動くわけではなく、次の Baker<T> によってECSのComponentデータへ変換される。

Baker<T>

Authoringの設定値を読み取り、Entity側のComponentへ変換するクラス。Authoringクラスの内部、または同じファイルに並べて書くことが多い。

using Unity.Entities;
using UnityEngine;

public sealed class MoveSpeedAuthoring : MonoBehaviour
{
    [SerializeField] private float _speed = 5f;

    private sealed class MoveSpeedBaker : Baker<MoveSpeedAuthoring>
    {
        public override void Bake(MoveSpeedAuthoring authoring)
        {
            Entity entity = GetEntity(TransformUsageFlags.Dynamic);
            AddComponent(entity, new MoveSpeed
            {
                Value = authoring._speed
            });
        }
    }
}

SubSceneの保存時やインポート時に自動で走り、GameObjectをEntityへと焼き付ける。Unity 6.6では、カスタムBakerが毎回同じ結果を出力するかを検証する EntitySceneImporterDeterminismChecker.Check() もエディタAPIとして追加されている。

GetEntity

Baker<T> の中で、対象のGameObjectに対応する Entity を取得するメソッド。

// 自分自身のGameObjectに対応するEntityを取得
Entity selfEntity = GetEntity(TransformUsageFlags.Dynamic);

// Inspectorで参照したPrefab GameObjectに対応するEntityを取得
Entity prefabEntity = GetEntity(authoring.BulletPrefab, TransformUsageFlags.Dynamic);

Authoring側で public GameObject BulletPrefab; のように参照を持たせておき、GetEntity で Entity に変換してComponentへ保存しておけば、実行時に Instantiate で高速に弾を生成できる。

TransformUsageFlags

GetEntity を呼ぶ際に、どのTransform系Componentが必要かを指定するフラグ。

// 実行時に移動・回転するオブジェクト
Entity dynamicEntity = GetEntity(TransformUsageFlags.Dynamic);

// 描画はされるが実行時に一切動かない背景オブジェクトなど
Entity renderableEntity = GetEntity(TransformUsageFlags.Renderable);

// 座標を持たない設定用データやマネージャ的なEntity
Entity dataOnlyEntity = GetEntity(TransformUsageFlags.None);

用途に合ったフラグを指定することで、不要な LocalTransform などのComponentが付くのを防ぎ、メモリと計算コストを節約できる。

SubScene

ECSのEntity群を配置・BakeするためのScene単位。通常のScene内に配置し、SubScene コンポーネントに別Sceneアセットを割り当てて使う。

Unity 6.6からは、専用のEntities Hierarchyウィンドウを開かなくても、標準のHierarchyウィンドウ上でSubSceneのダブルクリックによるOpen / CloseやReimport、さらに検索バーでの t:LocalTransform のようなComponent型フィルタリングがそのまま行えるようになっている。


EntityManager

World内のEntityの生成・破棄、Componentの追加・削除・値の取得などを直接行うための中心クラス。

Entity entity = state.EntityManager.CreateEntity();
state.EntityManager.AddComponentData(entity, new MoveSpeed { Value = 10f });

即時反映されるため分かりやすいが、Entityの生成・破棄やComponent構成の変更は Structural Change と呼ばれ、Chunk間のメモリ移動や実行中のJobの完了待ちを引き起こす。また、SystemAPI.Query の foreach ループ中に EntityManager で構造変更を行うと例外になるため、ループ中やJob内では次の EntityCommandBuffer を使う。

EntityCommandBuffer

Entityの生成・破棄やComponentの追加・削除といった構造変更コマンドを一旦記録しておき、後でまとめて再生する仕組み。略してECBとも呼ばれる。

var ecbSingleton = SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>();
EntityCommandBuffer ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged);

foreach (var (health, entity) in
         SystemAPI.Query<RefRO<Health>>().WithEntityAccess())
{
    if (health.ValueRO.Current <= 0f)
    {
        ecb.DestroyEntity(entity);
    }
}

Instantiate系は BeginSimulationEntityCommandBufferSystem.Singleton、Destroy系は EndSimulationEntityCommandBufferSystem.Singleton を使う。

自分で new EntityCommandBuffer(...) を作って Playback と Dispose を呼ぶこともできるが、システム標準の EndSimulationEntityCommandBufferSystem.Singleton(または BeginSimulationEntityCommandBufferSystem.Singleton)から取得すれば、フレームの区切りで自動的にPlaybackと破棄を行ってくれる。

並列Jobの中からECBに書き込む場合は、ecb.AsParallelWriter() に変換してJobへ渡す。

Unity 6.6での変更点:

  1. 生成時点で有効な Entity を返す: 6.5以前は ecb.CreateEntity() や ecb.Instantiate() が負のIndexを持つ「仮のPlaceholder Entity」を返し、Playback時に本物のIDへ書き換えていた。Unity 6.6からは、ECB記録時点で即座に有効な Entity を返すように改善された。
  2. MultiPlaybackの非推奨化: 同じECBを複数回再生する PlaybackPolicy.MultiPlayback はバグの温床になりやすいため、Unity 6.6で非推奨となった。ECBは1回だけ再生する前提で使う。

Instantiate

Bake済みのEntity Prefabを複製して新しいEntityを作る操作。EntityManager と EntityCommandBuffer の両方に用意されている。

Entity instance = ecb.Instantiate(spawner.ValueRO.BulletPrefab);
ecb.SetComponent(instance, LocalTransform.FromPosition(spawnPosition));

なお、従来は LinkedEntityGroup を持たないEntityを Instantiate した際、内部Componentが自分自身を参照していても複製元のEntityを指したままになる挙動があったが、現在は単体Entityの複製でも自己参照が複製先自身へ正しく張り替えられるよう修正されている。

DestroyEntity

指定したEntityをWorldから破棄する。

ecb.DestroyEntity(entity);

親子階層を持つEntityをまとめて消したい場合は、ルートEntityに LinkedEntityGroup が付いていることを確認したうえでルートを DestroyEntity すると、子Entityも一括で破棄される。

AddComponent / RemoveComponent / SetComponent

EntityのComponent構成を変更したり、既存のComponentの値を書き換えたりする操作。

// Componentを新しく付ける(構造変更)
ecb.AddComponent(entity, new Poisoned { DamagePerSecond = 2f });

// Componentを外す(構造変更)
ecb.RemoveComponent<Poisoned>(entity);

// 既に付いているComponentの値を上書きする(構造変更なし)
ecb.SetComponent(entity, new MoveSpeed { Value = 8f });

AddComponent と RemoveComponent はEntityのArchetypeが変わるため、Chunk間のデータ移動が発生する。フレームごとに頻繁にON/OFFを切り替えるような状態なら、AddComponent / RemoveComponent ではなく IEnableableComponent を使うほうが圧倒的に速い。


RequireForUpdate

特定のComponentがWorld内に1つ以上存在するときだけ、そのSystemの OnUpdate を走らせる指定。OnCreate の中で設定する。

public void OnCreate(ref SystemState state)
{
    state.RequireForUpdate<GameConfig>();
    state.RequireForUpdate<EnemyTag>();
}

SubSceneのロードが完了する前や、該当するEntityがまだ1体もスポーンしていないときに、OnUpdate が空回りしたり GetSingleton が例外を投げたりするのを防げる。GetSingleton<T>() を使うSystemでは、対になる state.RequireForUpdate<T>() を OnCreate に書いておかなければならない。

Singleton

World内にただ1つだけ存在するComponentを取得・更新する仕組み。全体設定やスポナー設定、物理ワールドなどでよく使う。

public void OnCreate(ref SystemState state)
{
    state.RequireForUpdate<GameConfig>();
}

public void OnUpdate(ref SystemState state)
{
    // 読み取り
    GameConfig config = SystemAPI.GetSingleton<GameConfig>();

    // 書き換えたい場合は GetSingletonRW を使う
    RefRW<GameConfig> configRW = SystemAPI.GetSingletonRW<GameConfig>();
    configRW.ValueRW.ElapsedWaveTime += SystemAPI.Time.DeltaTime;
}

シングルトン用の特別なインターフェースがあるわけではなく、通常の IComponentData を付けたEntityがWorld内に1体だけ存在すれば、SystemAPI.GetSingleton<T>() で取得できる。2体以上存在すると例外になるため注意する。

DynamicBuffer<T>

1つのEntityに対して、可変長の配列のようなデータを持たせる仕組み。要素となる構造体に IBufferElementData を実装する。

using Unity.Entities;
using Unity.Mathematics;

[InternalBufferCapacity(8)]
public struct WaypointElement : IBufferElementData
{
    public float3 Position;
}

[InternalBufferCapacity(8)] は「8要素まではChunk内のメモリに直接置き、それを超えたら自動でヒープメモリへ逃がす」という指定。インベントリ、移動経路のウェイポイント、そのフレームに受けたダメージ履歴リストなど、1つのEntityに複数個のデータが紐づく場面で使う。

foreach (var waypoints in
         SystemAPI.Query<DynamicBuffer<WaypointElement>>())
{
    for (int i = 0; i < waypoints.Length; i++)
    {
        float3 pos = waypoints[i].Position;
    }
}

IEnableableComponent

ComponentをEntityから外すことなく、ビットフラグの切り替えだけで有効・無効を切り替えられるインターフェース。IComponentData または IBufferElementData と合わせて実装する。

using Unity.Entities;

public struct Stunned : IComponentData, IEnableableComponent
{
    public float RemainingTime;
}

無効化されたComponentは、通常の SystemAPI.Query や IJobEntity の検索対象から自動的に外れる。しかもChunk間のメモリ移動が一切発生しないため、スタン状態、無敵状態、攻撃クールダウンなど、頻繁にON/OFFが切り替わる状態管理に非常に向いている。

// 有効・無効の切り替え
SystemAPI.SetComponentEnabled<Stunned>(entity, true);
SystemAPI.SetComponentEnabled<Stunned>(entity, false);

最初から無効状態でEntityに持たせておきたい場合は、Baker の中で AddComponent した直後に SetComponentEnabled<Stunned>(entity, false) を呼んでおく。

EntityQuery

「どのComponentを持ち、どのComponentを持たないEntityか」という検索条件そのものを表すオブジェクト。

EntityQuery query = SystemAPI.QueryBuilder()
    .WithAll<LocalTransform, MoveSpeed>()
    .WithNone<Stunned>()
    .Build();

int count = query.CalculateEntityCount();

通常のループ処理なら SystemAPI.Query で事足りるが、「条件に合うEntityの総数だけ知りたい(CalculateEntityCount)」「条件に合うEntityのComponentをまとめてネイティブ配列として取り出したい(ToComponentDataArray)」といった場面では SystemAPI.QueryBuilder() で EntityQuery を組み立てる。

ComponentLookup<T>

クエリのループ対象とは別の、特定の Entity が持っているComponentをID指定で直接引き当てるための辞書的アクセサ。

ComponentLookup<LocalTransform> transformLookup =
    SystemAPI.GetComponentLookup<LocalTransform>(isReadOnly: true);

if (transformLookup.TryGetRefRO(targetEntity, out RefRO<LocalTransform> targetTransform))
{
    float3 targetPos = targetTransform.ValueRO.Position;
}

たとえば「追尾弾のEntityが、ターゲットEntityの現在座標を参照したい」というときや、後述する物理衝突イベントのJob内で「ぶつかったEntity AとEntity Bが特定のComponentを持っているか調べる」ときに頻出する。存在しない可能性も考慮して、安全に参照を取得できる TryGetRefRO / TryGetRefRW / HasComponent を使う。


BlobAsset / BlobAssetReference<T>

複数のEntityから安全に共有できる、読み取り専用のImmutableなメモリ領域。Component側には BlobAssetReference<T> という参照ポインタ構造体を持たせる。

using Unity.Entities;

// 1. Blob内部のデータ構造
public struct WeaponStatsBlob
{
    public float AttackPower;
    public float Cooldown;
    public BlobArray<float> ComboMultipliers;
}

// 2. Entityに付けるComponent
public struct WeaponConfig : IComponentData
{
    public BlobAssetReference<WeaponStatsBlob> Stats;
}

通常、ECSのComponentには float[] や string のような参照型配列を入れられない。しかし、武器マスターデータやアニメーションカーブのサンプリング配列などを1万体の敵Entityそれぞれにコピーして持たせるとメモリが無駄になる。

そこで、Baker の中で BlobBuilder を使ってデータを連続したUnmanagedメモリ上に持たせ、その参照である BlobAssetReference<T> だけを各EntityのComponentに持たせる。

// Baker内での生成例
using var builder = new BlobBuilder(Allocator.Temp);
ref WeaponStatsBlob root = ref builder.ConstructRoot<WeaponStatsBlob>();
root.AttackPower = 25f;
root.Cooldown = 0.5f;

BlobBuilderArray<float> combo = builder.Allocate(ref root.ComboMultipliers, 3);
combo[0] = 1.0f;
combo[1] = 1.2f;
combo[2] = 1.8f;

BlobAssetReference<WeaponStatsBlob> blobRef =
    builder.CreateBlobAssetReference<WeaponStatsBlob>(Allocator.Persistent);

// Bakerの管理下に登録(破棄や重複排除を自動化)
AddBlobAsset(ref blobRef, out _);
AddComponent(entity, new WeaponConfig { Stats = blobRef });

読み取り専用かつ完全にUnmanagedなメモリ配置になっているため、Burstコンパイルされた並列Jobの内部からでも、config.Stats.Value.ComboMultipliers[0] のようにノーコストかつ安全に同時アクセスできる。従来のGameObject開発で ScriptableObject に持たせていた読み取り専用のマスターデータは、ECSではこの BlobAsset に置き換える。

ISharedComponentData

同じ値を持つEntity同士を、メモリ上で同じChunkにグループ分けするための特殊なComponent。

using System;
using Unity.Entities;

public struct TeamSharedFilter : ISharedComponentData, IEquatable<TeamSharedFilter>
{
    public int TeamId;
    public int RenderLayer;

    public bool Equals(TeamSharedFilter other)
    {
        return TeamId == other.TeamId && RenderLayer == other.RenderLayer;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(TeamId, RenderLayer);
    }
}

通常の IComponentData はEntityごとに値が違っても同じChunkに並んで格納されるが、ISharedComponentData は値が同じEntityだけを同じChunkに集めるという働きをする。値自体はChunkの外のテーブルで1つだけ管理され、Chunk単位で一括フィルタリング(query.SetSharedComponentFilter(...))ができる。

使いどころと注意点:

  • 向いている場面: 描画メッシュ・マテリアルのバッチング分類や、少数のチーム分けのように、種類のバリエーションが少なく、同じ種類のEntityをまとめて処理したいケース。
  • 向いていない場面: Entityごとにバラバラな値を持たせたり、毎フレーム値を書き換えたりするケース。値を変更すると別Chunkへの移動が発生し、さらに種類が増えすぎるとスカスカのChunkが大量にできてメモリ効率が悪化する。
  • Unity 6.6での変更点: マネージド型を含む ISharedComponentData および *Managed 系のShared Component APIが非推奨となり、コンパイラ警告 EA0017 が出るようになった。Unityオブジェクトを参照したい場合は、Unmanagedな struct にしたうえで UnityObjectRef<T> を使う。

ICleanupComponentData

Entityが DestroyEntity されたとき、必要な後始末が終わるまでEntityの完全消去を食い止めるためのComponent。

using Unity.Entities;

public struct ResourceCleanup : ICleanupComponentData
{
    public int AllocatedHandleId;
}

ICleanupComponentData が付いているEntityに対して DestroyEntity を呼ぶと、まず通常の IComponentData だけがすべて剥がされ、ICleanupComponentData だけが残った破棄待ち状態のEntityになる。

後始末用のSystemでResourceCleanup は持っているが、通常のComponentは既に失っているEntityをクエリで検出し、外部リソースの解放処理を行ったあとで RemoveComponent<ResourceCleanup> を呼ぶと、その時点でEntity自体も完全に消滅する。


PhysicsVelocity / PhysicsMass

Unity.Physics パッケージでRigidbodyの移動速度や質量特性を扱うComponent。

エディタ上でGameObjectに標準の Rigidbody や Collider を付けてBakeすると、裏側で自動的にこれらのComponentへ変換される。

using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Physics.Extensions;

foreach (var (velocity, mass) in
         SystemAPI.Query<
             RefRW<PhysicsVelocity>,
             RefRO<PhysicsMass>>())
{
    // 線形速度(Linear)を直接書き換える
    velocity.ValueRW.Linear = new float3(0f, 5f, 0f);

    // 回転速度(Angular)を止める
    velocity.ValueRW.Angular = float3.zero;

    // 拡張メソッド(Unity.Physics.Extensions)でインパルスを加える
    velocity.ValueRW.ApplyLinearImpulse(mass.ValueRO, new float3(0f, 10f, 0f));
}

物理挙動を持つEntityを動かすときは、LocalTransform.Position を直接書き換えるのではなく、PhysicsVelocity.Linear や PhysicsVelocity.Angular を操作する。座標を直接書き換えると物理エンジンの速度計算と矛盾し、衝突判定をすり抜けたり吹っ飛んだりする原因になる。

PhysicsWorldSingleton

空間に対するRayCastや球体判定など、物理ワールドへのクエリを投げるためのシングルトンComponent。

using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics;

public void OnCreate(ref SystemState state)
{
    state.RequireForUpdate<PhysicsWorldSingleton>();
}

public void OnUpdate(ref SystemState state)
{
    PhysicsWorldSingleton physicsWorld = SystemAPI.GetSingleton<PhysicsWorldSingleton>();

    RaycastInput input = new RaycastInput
    {
        Start = new float3(0f, 1f, 0f),
        End = new float3(0f, 1f, 20f),
        Filter = CollisionFilter.Default
    };

    if (physicsWorld.CastRay(input, out RaycastHit hit))
    {
        Entity hitEntity = hit.Entity;
        float3 hitPosition = hit.Position;
    }
}

GameObjectの Physics.Raycast と違い、ECSでは PhysicsWorldSingleton を取得して、その CastRay や CalculateDistance メソッドを呼ぶ。すべて値型で完結しているため、PhysicsWorldSingleton を IJobEntity のフィールドに渡せば、数千本のレイキャストをワーカースレッドで並列実行することもできる。

SimulationSingleton

物理ステップ内で発生したCollision EventやTrigger Eventのストリームを受け取り、イベント処理JobをスケジュールするためのシングルトンComponent。

SimulationSingleton simulation = SystemAPI.GetSingleton<SimulationSingleton>();

GameObjectでは OnCollisionEnter や OnTriggerEnter というメソッドを各スクリプトに書くが、Unity Physicsでは「そのフレームに起きたすべての衝突ペアのリスト」が物理エンジンから出力される。それを SimulationSingleton 経由で ICollisionEventsJob / ITriggerEventsJob に流し込んで一括処理する。

また、衝突やトリガーのイベント処理を行うSystemは、物理計算の直後に走るよう [UpdateInGroup(typeof(FixedStepSimulationSystemGroup))] と [UpdateAfter(typeof(PhysicsSystemGroup))] を付けておく。

ICollisionEventsJob

物理的な跳ね返りを伴うCollisionが発生したペアを受け取って処理するJobインターフェース。Unity.Physics と Unity.Physics.Systems 名前空間を使う。

※ このイベントを受け取るには、Authoring側のColliderの設定で Collision Response を Collide Raise Collision Events にしておく必要がある。

using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Physics;
using Unity.Physics.Systems;

[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
[UpdateAfter(typeof(PhysicsSystemGroup))]
public partial struct ProjectileHitSystem : ISystem
{
    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        state.RequireForUpdate<SimulationSingleton>();
    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        state.Dependency = new CollisionEventJob
        {
            ProjectileLookup = SystemAPI.GetComponentLookup<ProjectileTag>(isReadOnly: true),
            HealthLookup = SystemAPI.GetComponentLookup<Health>(isReadOnly: false)
        }.Schedule(SystemAPI.GetSingleton<SimulationSingleton>(), state.Dependency);
    }
}

[BurstCompile]
public struct CollisionEventJob : ICollisionEventsJob
{
    [ReadOnly] public ComponentLookup<ProjectileTag> ProjectileLookup;
    public ComponentLookup<Health> HealthLookup;

    public void Execute(CollisionEvent collisionEvent)
    {
        Entity entityA = collisionEvent.EntityA;
        Entity entityB = collisionEvent.EntityB;

        // AとBのどちらが弾でどちらがダメージ対象か分からないため、両方向をチェックする
        if (ProjectileLookup.HasComponent(entityA) && HealthLookup.HasComponent(entityB))
        {
            Health health = HealthLookup[entityB];
            health.Current -= 10f;
            HealthLookup[entityB] = health;
        }
        else if (ProjectileLookup.HasComponent(entityB) && HealthLookup.HasComponent(entityA))
        {
            Health health = HealthLookup[entityA];
            health.Current -= 10f;
            HealthLookup[entityA] = health;
        }
    }
}

Execute(CollisionEvent collisionEvent) には、ぶつかった2つのEntityである EntityA と EntityB が渡ってくる。どちらが EntityA になるかは決まっていないため、ComponentLookup<T> で両方のパターンを判定するのがお約束の形になる。

ITriggerEventsJob

物理的な反発を伴わず、領域に重なったことだけを検知するTriggerを処理するJobインターフェース。

※ Authoring側のColliderで Is Trigger にチェックを入れる必要がある。

using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Physics;

[BurstCompile]
public struct PickupTriggerJob : ITriggerEventsJob
{
    [ReadOnly] public ComponentLookup<PlayerTag> PlayerLookup;
    [ReadOnly] public ComponentLookup<CoinTag> CoinLookup;
    public EntityCommandBuffer Ecb;

    public void Execute(TriggerEvent triggerEvent)
    {
        Entity entityA = triggerEvent.EntityA;
        Entity entityB = triggerEvent.EntityB;

        if (PlayerLookup.HasComponent(entityA) && CoinLookup.HasComponent(entityB))
        {
            Ecb.DestroyEntity(entityB);
        }
        else if (PlayerLookup.HasComponent(entityB) && CoinLookup.HasComponent(entityA))
        {
            Ecb.DestroyEntity(entityA);
        }
    }
}

構造は ICollisionEventsJob とほぼ同じで、アイテム回収エリア、ダメージ床、センサー範囲の判定などに使う。


IDebugOnAdded / IDebugOnRemoved

Unity 6.6で新設されたデバッグ用インターフェース。特定のComponentがEntityに追加された瞬間、または削除された瞬間に、静的メソッドのコールバックを即座に発火させる。

using Unity.Burst;
using Unity.Entities;
using UnityEngine;

[BurstCompile]
public struct Health : IComponentData, IDebugOnAdded, IDebugOnRemoved
{
    public float Value;

    public static void OnAdded(Entity entity, in Health component)
    {
        Debug.Log($"Health added to {entity}: {component.Value}");
    }

    public static void OnRemoved(Entity entity, in Health component)
    {
        Debug.Log($"Health removed from {entity}: {component.Value}");
    }
}

Unity 6.6では従来の重い Journaling 機能が非推奨となり、代わりにこの軽量なライフサイクルコールバックが導入された。

  • 使い道: 「なぜか勝手にComponentが消えている」「どのSystemがこのComponentを付けたのか分からない」というときに、OnAdded / OnRemoved 内にブレークポイントを張れば、その瞬間のコールスタックを特定できる。
  • 注意点: エディタおよびDevelopment Buildでのみ動作し、Release Buildでは自動的に除外される。そのため本番ビルドのパフォーマンスには影響しないが、リソース解放などの本処理に使ってはならない。

IJobEntity

EntityごとのComponent処理を、マルチスレッド対応のJobとして定義する仕組み。partial struct で作成し、Execute メソッドの引数に受け取りたいComponentを並べる。

using Unity.Burst;
using Unity.Entities;
using Unity.Transforms;

[BurstCompile]
public partial struct MoveJob : IJobEntity
{
    public float DeltaTime;

    private void Execute(ref LocalTransform transform, in MoveSpeed speed)
    {
        transform.Position.x += speed.Value * DeltaTime;
    }
}

引数の ref が読み書き、in が読み取り専用を表す。呼び出す側の ISystem.OnUpdate では以下のようにスケジュールする。

[BurstCompile]
public void OnUpdate(ref SystemState state)
{
    new MoveJob
    {
        DeltaTime = SystemAPI.Time.DeltaTime
    }.ScheduleParallel();
}

  • .Run() : メインスレッドで即座に実行する。
  • .Schedule() : ワーカースレッド1つで非同期実行する。
  • .ScheduleParallel() : 複数のワーカースレッドにChunk単位で分散して並列実行する。

Entity数が少ない処理や試作段階では SystemAPI.Query で書き、数千〜数万体の計算負荷がかかる部分を IJobEntity + .ScheduleParallel() に切り出す、という使い分けがやりやすい。なお、IJobEntity には自動でBurstが付かないため、必ず構造体に [BurstCompile] を付ける。

BurstCompile

C#の数値計算コード(ISystem や IJobEntity)を、LLVMベースのBurstコンパイラによって高度に最適化されたネイティブ機械語へ変換する属性。

public partial struct MySystem : ISystem
{
    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        // Burstコンパイルされる処理
    }
}

ISystem では、OnCreate / OnUpdate / OnDestroy の各メソッドに [BurstCompile] を付ける。一方、IJobEntity や ITriggerEventsJob ではJob構造体の宣言に [BurstCompile] を付けるだけで Execute もBurst対象になる。

UpdateInGroup / UpdateBefore / UpdateAfter

Systemがどのグループで、どのSystemの前後で実行されるかを制御する属性。

using Unity.Entities;
using Unity.Transforms;

[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateBefore(typeof(TransformSystemGroup))]
public partial struct MoveSystem : ISystem
{
    public void OnUpdate(ref SystemState state) { }
}

主な標準グループは以下の通り。

  1. InitializationSystemGroup(初期化・入力取得など)
  2. SimulationSystemGroup(ゲームロジック・移動・座標計算など。指定省略時のデフォルト)
  • この内部に固定時間ステップで動く FixedStepSimulationSystemGroup や、座標行列を計算する TransformSystemGroup が含まれる。
  1. PresentationSystemGroup(描画前の準備など)

Unity 6.6ではSystemsウィンドウが刷新され、新たにScheduling列が追加された。選択したSystemに対して UpdateBefore / UpdateAfter で直接依存関係にあるSystemが一目でラベル表示されるため、実行順の確認がかなり楽になっている。


実戦的な組み合わせ

最後に、今回追加した BlobAsset、PhysicsVelocity、ITriggerEventsJob、EntityCommandBuffer を繋げた「物理移動する弾が敵に当たったら、BlobAssetの攻撃力を参照してダメージを与え、弾自身を消す」というUnity 6.6以降向けの実戦的な構成を載せておく。

1. データ定義(ComponentとBlobAsset)

using Unity.Entities;

// 弾のマスターデータ(BlobAssetとして共有)
public struct BulletStatsBlob
{
    public float Speed;
    public float Damage;
}

// 弾Entityに付けるComponent
public struct BulletComponent : IComponentData
{
    public BlobAssetReference<BulletStatsBlob> Stats;
}

// 敵のHP
public struct EnemyHealth : IComponentData
{
    public float Current;
}

2. AuthoringとBaker(BlobAssetを生成して弾Prefabに焼き付ける)

using Unity.Collections;
using Unity.Entities;
using UnityEngine;

public sealed class BulletAuthoring : MonoBehaviour
{
    [SerializeField] private float _speed = 20f;
    [SerializeField] private float _damage = 15f;

    private sealed class BulletBaker : Baker<BulletAuthoring>
    {
        public override void Bake(BulletAuthoring authoring)
        {
            Entity entity = GetEntity(TransformUsageFlags.Dynamic);

            // BlobAssetの構築
            using var builder = new BlobBuilder(Allocator.Temp);
            ref BulletStatsBlob root = ref builder.ConstructRoot<BulletStatsBlob>();
            root.Speed = authoring._speed;
            root.Damage = authoring._damage;

            var blobRef = builder.CreateBlobAssetReference<BulletStatsBlob>(Allocator.Persistent);
            AddBlobAsset(ref blobRef, out _);

            AddComponent(entity, new BulletComponent { Stats = blobRef });
        }
    }
}

3. 物理速度の更新(BlobAssetの速度でPhysicsVelocityを走らせる)

using Unity.Burst;
using Unity.Entities;
using Unity.Physics;
using Unity.Transforms;

[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
[UpdateBefore(typeof(PhysicsSystemGroup))]
public partial struct BulletMoveSystem : ISystem
{
    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        foreach (var (velocity, transform, bullet) in
                 SystemAPI.Query<
                     RefRW<PhysicsVelocity>,
                     RefRO<LocalTransform>,
                     RefRO<BulletComponent>>())
        {
            float speed = bullet.ValueRO.Stats.Value.Speed;
            velocity.ValueRW.Linear = transform.ValueRO.Forward() * speed;
        }
    }
}

4. トリガー衝突判定とダメージ・弾破棄(ITriggerEventsJob + ECB)

using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Physics;
using Unity.Physics.Systems;

[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
[UpdateAfter(typeof(PhysicsSystemGroup))]
public partial struct BulletHitSystem : ISystem
{
    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        state.RequireForUpdate<SimulationSingleton>();
        state.RequireForUpdate<EndFixedStepSimulationEntityCommandBufferSystem.Singleton>();
    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        var ecbSingleton = SystemAPI.GetSingleton<EndFixedStepSimulationEntityCommandBufferSystem.Singleton>();
        EntityCommandBuffer ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged);

        state.Dependency = new BulletTriggerJob
        {
            BulletLookup = SystemAPI.GetComponentLookup<BulletComponent>(isReadOnly: true),
            EnemyHealthLookup = SystemAPI.GetComponentLookup<EnemyHealth>(isReadOnly: false),
            Ecb = ecb
        }.Schedule(SystemAPI.GetSingleton<SimulationSingleton>(), state.Dependency);
    }
}

[BurstCompile]
public struct BulletTriggerJob : ITriggerEventsJob
{
    [ReadOnly] public ComponentLookup<BulletComponent> BulletLookup;
    public ComponentLookup<EnemyHealth> EnemyHealthLookup;
    public EntityCommandBuffer Ecb;

    public void Execute(TriggerEvent triggerEvent)
    {
        Entity entityA = triggerEvent.EntityA;
        Entity entityB = triggerEvent.EntityB;

        if (BulletLookup.TryGetRefRO(entityA, out var bulletA) &&
            EnemyHealthLookup.TryGetRefRW(entityB, out var enemyB))
        {
            enemyB.ValueRW.Current -= bulletA.ValueRO.Stats.Value.Damage;
            Ecb.DestroyEntity(entityA);
        }
        else if (BulletLookup.TryGetRefRO(entityB, out var bulletB) &&
                 EnemyHealthLookup.TryGetRefRW(entityA, out var enemyA))
        {
            enemyA.ValueRW.Current -= bulletB.ValueRO.Stats.Value.Damage;
            Ecb.DestroyEntity(entityB);
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?