[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72XQHM1S9S0GDWE9PEB08M9":3,"skill-same:01M72XQHM1S9S0GDWE9PEB08M9":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":28,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M72XQHM1S9S0GDWE9PEB08M9","unity-ecs-patterns",null,"Master Unity ECS (Entity Component System) with DOTS, Jobs, and Burst for high-performance game development. Use when building data-oriented games, optimizing performance, or working with large entity counts.","steph-frtech\u002Fclaude-code-up","steph-frtech","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F198466323?v=4","01M72XD213FVQA2QXRGTJFKHE1","01M72XD227AANJ993SQTNZB1CK",1,"MIT","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fgame-development\u002Fskills\u002Funity-ecs-patterns\u002FSKILL.md",[],[],"2026-11-10 22:39:42",false,"---\nname: unity-ecs-patterns\ndescription: Master Unity ECS (Entity Component System) with DOTS, Jobs, and Burst for high-performance game development. Use when building data-oriented games, optimizing performance, or working with large entity counts.\n---\n\n# Unity ECS Patterns\n\nProduction patterns for Unity's Data-Oriented Technology Stack (DOTS) including Entity Component System, Job System, and Burst Compiler.\n\n## When to Use This Skill\n\n- Building high-performance Unity games\n- Managing thousands of entities efficiently\n- Implementing data-oriented game systems\n- Optimizing CPU-bound game logic\n- Converting OOP game code to ECS\n- Using Jobs and Burst for parallelization\n\n## Core Concepts\n\n### 1. ECS vs OOP\n\n| Aspect      | Traditional OOP   | ECS\u002FDOTS        |\n| ----------- | ----------------- | --------------- |\n| Data layout | Object-oriented   | Data-oriented   |\n| Memory      | Scattered         | Contiguous      |\n| Processing  | Per-object        | Batched         |\n| Scaling     | Poor with count   | Linear scaling  |\n| Best for    | Complex behaviors | Mass simulation |\n\n### 2. DOTS Components\n\n```\nEntity: Lightweight ID (no data)\nComponent: Pure data (no behavior)\nSystem: Logic that processes components\nWorld: Container for entities\nArchetype: Unique combination of components\nChunk: Memory block for same-archetype entities\n```\n\n## Patterns\n\n### Pattern 1: Basic ECS Setup\n\n```csharp\nusing Unity.Entities;\nusing Unity.Mathematics;\nusing Unity.Transforms;\nusing Unity.Burst;\nusing Unity.Collections;\n\n\u002F\u002F Component: Pure data, no methods\npublic struct Speed : IComponentData\n{\n    public float Value;\n}\n\npublic struct Health : IComponentData\n{\n    public float Current;\n    public float Max;\n}\n\npublic struct Target : IComponentData\n{\n    public Entity Value;\n}\n\n\u002F\u002F Tag component (zero-size marker)\npublic struct EnemyTag : IComponentData { }\npublic struct PlayerTag : IComponentData { }\n\n\u002F\u002F Buffer component (variable-size array)\n[InternalBufferCapacity(8)]\npublic struct InventoryItem : IBufferElementData\n{\n    public int ItemId;\n    public int Quantity;\n}\n\n\u002F\u002F Shared component (grouped entities)\npublic struct TeamId : ISharedComponentData\n{\n    public int Value;\n}\n```\n\n### Pattern 2: Systems with ISystem (Recommended)\n\n```csharp\nusing Unity.Entities;\nusing Unity.Transforms;\nusing Unity.Mathematics;\nusing Unity.Burst;\n\n\u002F\u002F ISystem: Unmanaged, Burst-compatible, highest performance\n[BurstCompile]\npublic partial struct MovementSystem : ISystem\n{\n    [BurstCompile]\n    public void OnCreate(ref SystemState state)\n    {\n        \u002F\u002F Require components before system runs\n        state.RequireForUpdate\u003CSpeed>();\n    }\n\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        float deltaTime = SystemAPI.Time.DeltaTime;\n\n        \u002F\u002F Simple foreach - auto-generates job\n        foreach (var (transform, speed) in\n            SystemAPI.Query\u003CRefRW\u003CLocalTransform>, RefRO\u003CSpeed>>())\n        {\n            transform.ValueRW.Position +=\n                new float3(0, 0, speed.ValueRO.Value * deltaTime);\n        }\n    }\n\n    [BurstCompile]\n    public void OnDestroy(ref SystemState state) { }\n}\n\n\u002F\u002F With explicit job for more control\n[BurstCompile]\npublic partial struct MovementJobSystem : ISystem\n{\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        var job = new MoveJob\n        {\n            DeltaTime = SystemAPI.Time.DeltaTime\n        };\n\n        state.Dependency = job.ScheduleParallel(state.Dependency);\n    }\n}\n\n[BurstCompile]\npublic partial struct MoveJob : IJobEntity\n{\n    public float DeltaTime;\n\n    void Execute(ref LocalTransform transform, in Speed speed)\n    {\n        transform.Position += new float3(0, 0, speed.Value * DeltaTime);\n    }\n}\n```\n\n### Pattern 3: Entity Queries\n\n```csharp\n[BurstCompile]\npublic partial struct QueryExamplesSystem : ISystem\n{\n    private EntityQuery _enemyQuery;\n\n    public void OnCreate(ref SystemState state)\n    {\n        \u002F\u002F Build query manually for complex cases\n        _enemyQuery = new EntityQueryBuilder(Allocator.Temp)\n            .WithAll\u003CEnemyTag, Health, LocalTransform>()\n            .WithNone\u003CDead>()\n            .WithOptions(EntityQueryOptions.FilterWriteGroup)\n            .Build(ref state);\n    }\n\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        \u002F\u002F SystemAPI.Query - simplest approach\n        foreach (var (health, entity) in\n            SystemAPI.Query\u003CRefRW\u003CHealth>>()\n                .WithAll\u003CEnemyTag>()\n                .WithEntityAccess())\n        {\n            if (health.ValueRO.Current \u003C= 0)\n            {\n                \u002F\u002F Mark for destruction\n                SystemAPI.GetSingleton\u003CEndSimulationEntityCommandBufferSystem.Singleton>()\n                    .CreateCommandBuffer(state.WorldUnmanaged)\n                    .DestroyEntity(entity);\n            }\n        }\n\n        \u002F\u002F Get count\n        int enemyCount = _enemyQuery.CalculateEntityCount();\n\n        \u002F\u002F Get all entities\n        var enemies = _enemyQuery.ToEntityArray(Allocator.Temp);\n\n        \u002F\u002F Get component arrays\n        var healths = _enemyQuery.ToComponentDataArray\u003CHealth>(Allocator.Temp);\n    }\n}\n```\n\n### Pattern 4: Entity Command Buffers (Structural Changes)\n\n```csharp\n\u002F\u002F Structural changes (create\u002Fdestroy\u002Fadd\u002Fremove) require command buffers\n[BurstCompile]\n[UpdateInGroup(typeof(SimulationSystemGroup))]\npublic partial struct SpawnSystem : ISystem\n{\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        var ecbSingleton = SystemAPI.GetSingleton\u003CBeginSimulationEntityCommandBufferSystem.Singleton>();\n        var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged);\n\n        foreach (var (spawner, transform) in\n            SystemAPI.Query\u003CRefRW\u003CSpawner>, RefRO\u003CLocalTransform>>())\n        {\n            spawner.ValueRW.Timer -= SystemAPI.Time.DeltaTime;\n\n            if (spawner.ValueRO.Timer \u003C= 0)\n            {\n                spawner.ValueRW.Timer = spawner.ValueRO.Interval;\n\n                \u002F\u002F Create entity (deferred until sync point)\n                Entity newEntity = ecb.Instantiate(spawner.ValueRO.Prefab);\n\n                \u002F\u002F Set component values\n                ecb.SetComponent(newEntity, new LocalTransform\n                {\n                    Position = transform.ValueRO.Position,\n                    Rotation = quaternion.identity,\n                    Scale = 1f\n                });\n\n                \u002F\u002F Add component\n                ecb.AddComponent(newEntity, new Speed { Value = 5f });\n            }\n        }\n    }\n}\n\n\u002F\u002F Parallel ECB usage\n[BurstCompile]\npublic partial struct ParallelSpawnJob : IJobEntity\n{\n    public EntityCommandBuffer.ParallelWriter ECB;\n\n    void Execute([EntityIndexInQuery] int index, in Spawner spawner)\n    {\n        Entity e = ECB.Instantiate(index, spawner.Prefab);\n        ECB.AddComponent(index, e, new Speed { Value = 5f });\n    }\n}\n```\n\n### Pattern 5: Aspect (Grouping Components)\n\n```csharp\nusing Unity.Entities;\nusing Unity.Transforms;\nusing Unity.Mathematics;\n\n\u002F\u002F Aspect: Groups related components for cleaner code\npublic readonly partial struct CharacterAspect : IAspect\n{\n    public readonly Entity Entity;\n\n    private readonly RefRW\u003CLocalTransform> _transform;\n    private readonly RefRO\u003CSpeed> _speed;\n    private readonly RefRW\u003CHealth> _health;\n\n    \u002F\u002F Optional component\n    [Optional]\n    private readonly RefRO\u003CShield> _shield;\n\n    \u002F\u002F Buffer\n    private readonly DynamicBuffer\u003CInventoryItem> _inventory;\n\n    public float3 Position\n    {\n        get => _transform.ValueRO.Position;\n        set => _transform.ValueRW.Position = value;\n    }\n\n    public float CurrentHealth => _health.ValueRO.Current;\n    public float MaxHealth => _health.ValueRO.Max;\n    public float MoveSpeed => _speed.ValueRO.Value;\n\n    public bool HasShield => _shield.IsValid;\n    public float ShieldAmount => HasShield ? _shield.ValueRO.Amount : 0f;\n\n    public void TakeDamage(float amount)\n    {\n        float remaining = amount;\n\n        if (HasShield && _shield.ValueRO.Amount > 0)\n        {\n            \u002F\u002F Shield absorbs damage first\n            remaining = math.max(0, amount - _shield.ValueRO.Amount);\n        }\n\n        _health.ValueRW.Current = math.max(0, _health.ValueRO.Current - remaining);\n    }\n\n    public void Move(float3 direction, float deltaTime)\n    {\n        _transform.ValueRW.Position += direction * _speed.ValueRO.Value * deltaTime;\n    }\n\n    public void AddItem(int itemId, int quantity)\n    {\n        _inventory.Add(new InventoryItem { ItemId = itemId, Quantity = quantity });\n    }\n}\n\n\u002F\u002F Using aspect in system\n[BurstCompile]\npublic partial struct CharacterSystem : ISystem\n{\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        float dt = SystemAPI.Time.DeltaTime;\n\n        foreach (var character in SystemAPI.Query\u003CCharacterAspect>())\n        {\n            character.Move(new float3(1, 0, 0), dt);\n\n            if (character.CurrentHealth \u003C character.MaxHealth * 0.5f)\n            {\n                \u002F\u002F Low health logic\n            }\n        }\n    }\n}\n```\n\n### Pattern 6: Singleton Components\n\n```csharp\n\u002F\u002F Singleton: Exactly one entity with this component\npublic struct GameConfig : IComponentData\n{\n    public float DifficultyMultiplier;\n    public int MaxEnemies;\n    public float SpawnRate;\n}\n\npublic struct GameState : IComponentData\n{\n    public int Score;\n    public int Wave;\n    public float TimeRemaining;\n}\n\n\u002F\u002F Create singleton on world creation\npublic partial struct GameInitSystem : ISystem\n{\n    public void OnCreate(ref SystemState state)\n    {\n        var entity = state.EntityManager.CreateEntity();\n        state.EntityManager.AddComponentData(entity, new GameConfig\n        {\n            DifficultyMultiplier = 1.0f,\n            MaxEnemies = 100,\n            SpawnRate = 2.0f\n        });\n        state.EntityManager.AddComponentData(entity, new GameState\n        {\n            Score = 0,\n            Wave = 1,\n            TimeRemaining = 120f\n        });\n    }\n}\n\n\u002F\u002F Access singleton in system\n[BurstCompile]\npublic partial struct ScoreSystem : ISystem\n{\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        \u002F\u002F Read singleton\n        var config = SystemAPI.GetSingleton\u003CGameConfig>();\n\n        \u002F\u002F Write singleton\n        ref var gameState = ref SystemAPI.GetSingletonRW\u003CGameState>().ValueRW;\n        gameState.TimeRemaining -= SystemAPI.Time.DeltaTime;\n\n        \u002F\u002F Check exists\n        if (SystemAPI.HasSingleton\u003CGameConfig>())\n        {\n            \u002F\u002F ...\n        }\n    }\n}\n```\n\n### Pattern 7: Baking (Converting GameObjects)\n\n```csharp\nusing Unity.Entities;\nusing UnityEngine;\n\n\u002F\u002F Authoring component (MonoBehaviour in Editor)\npublic class EnemyAuthoring : MonoBehaviour\n{\n    public float Speed = 5f;\n    public float Health = 100f;\n    public GameObject ProjectilePrefab;\n\n    class Baker : Baker\u003CEnemyAuthoring>\n    {\n        public override void Bake(EnemyAuthoring authoring)\n        {\n            var entity = GetEntity(TransformUsageFlags.Dynamic);\n\n            AddComponent(entity, new Speed { Value = authoring.Speed });\n            AddComponent(entity, new Health\n            {\n                Current = authoring.Health,\n                Max = authoring.Health\n            });\n            AddComponent(entity, new EnemyTag());\n\n            if (authoring.ProjectilePrefab != null)\n            {\n                AddComponent(entity, new ProjectilePrefab\n                {\n                    Value = GetEntity(authoring.ProjectilePrefab, TransformUsageFlags.Dynamic)\n                });\n            }\n        }\n    }\n}\n\n\u002F\u002F Complex baking with dependencies\npublic class SpawnerAuthoring : MonoBehaviour\n{\n    public GameObject[] Prefabs;\n    public float Interval = 1f;\n\n    class Baker : Baker\u003CSpawnerAuthoring>\n    {\n        public override void Bake(SpawnerAuthoring authoring)\n        {\n            var entity = GetEntity(TransformUsageFlags.Dynamic);\n\n            AddComponent(entity, new Spawner\n            {\n                Interval = authoring.Interval,\n                Timer = 0f\n            });\n\n            \u002F\u002F Bake buffer of prefabs\n            var buffer = AddBuffer\u003CSpawnPrefabElement>(entity);\n            foreach (var prefab in authoring.Prefabs)\n            {\n                buffer.Add(new SpawnPrefabElement\n                {\n                    Prefab = GetEntity(prefab, TransformUsageFlags.Dynamic)\n                });\n            }\n\n            \u002F\u002F Declare dependencies\n            DependsOn(authoring.Prefabs);\n        }\n    }\n}\n```\n\n### Pattern 8: Jobs with Native Collections\n\n```csharp\nusing Unity.Jobs;\nusing Unity.Collections;\nusing Unity.Burst;\nusing Unity.Mathematics;\n\n[BurstCompile]\npublic struct SpatialHashJob : IJobParallelFor\n{\n    [ReadOnly]\n    public NativeArray\u003Cfloat3> Positions;\n\n    \u002F\u002F Thread-safe write to hash map\n    public NativeParallelMultiHashMap\u003Cint, int>.ParallelWriter HashMap;\n\n    public float CellSize;\n\n    public void Execute(int index)\n    {\n        float3 pos = Positions[index];\n        int hash = GetHash(pos);\n        HashMap.Add(hash, index);\n    }\n\n    int GetHash(float3 pos)\n    {\n        int x = (int)math.floor(pos.x \u002F CellSize);\n        int y = (int)math.floor(pos.y \u002F CellSize);\n        int z = (int)math.floor(pos.z \u002F CellSize);\n        return x * 73856093 ^ y * 19349663 ^ z * 83492791;\n    }\n}\n\n[BurstCompile]\npublic partial struct SpatialHashSystem : ISystem\n{\n    private NativeParallelMultiHashMap\u003Cint, int> _hashMap;\n\n    public void OnCreate(ref SystemState state)\n    {\n        _hashMap = new NativeParallelMultiHashMap\u003Cint, int>(10000, Allocator.Persistent);\n    }\n\n    public void OnDestroy(ref SystemState state)\n    {\n        _hashMap.Dispose();\n    }\n\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        var query = SystemAPI.QueryBuilder()\n            .WithAll\u003CLocalTransform>()\n            .Build();\n\n        int count = query.CalculateEntityCount();\n\n        \u002F\u002F Resize if needed\n        if (_hashMap.Capacity \u003C count)\n        {\n            _hashMap.Capacity = count * 2;\n        }\n\n        _hashMap.Clear();\n\n        \u002F\u002F Get positions\n        var positions = query.ToComponentDataArray\u003CLocalTransform>(Allocator.TempJob);\n        var posFloat3 = new NativeArray\u003Cfloat3>(count, Allocator.TempJob);\n\n        for (int i = 0; i \u003C count; i++)\n        {\n            posFloat3[i] = positions[i].Position;\n        }\n\n        \u002F\u002F Build hash map\n        var hashJob = new SpatialHashJob\n        {\n            Positions = posFloat3,\n            HashMap = _hashMap.AsParallelWriter(),\n            CellSize = 10f\n        };\n\n        state.Dependency = hashJob.Schedule(count, 64, state.Dependency);\n\n        \u002F\u002F Cleanup\n        positions.Dispose(state.Dependency);\n        posFloat3.Dispose(state.Dependency);\n    }\n}\n```\n\n## Performance Tips\n\n```csharp\n\u002F\u002F 1. Use Burst everywhere\n[BurstCompile]\npublic partial struct MySystem : ISystem { }\n\n\u002F\u002F 2. Prefer IJobEntity over manual iteration\n[BurstCompile]\npartial struct OptimizedJob : IJobEntity\n{\n    void Execute(ref LocalTransform transform) { }\n}\n\n\u002F\u002F 3. Schedule parallel when possible\nstate.Dependency = job.ScheduleParallel(state.Dependency);\n\n\u002F\u002F 4. Use ScheduleParallel with chunk iteration\n[BurstCompile]\npartial struct ChunkJob : IJobChunk\n{\n    public ComponentTypeHandle\u003CHealth> HealthHandle;\n\n    public void Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex,\n        bool useEnabledMask, in v128 chunkEnabledMask)\n    {\n        var healths = chunk.GetNativeArray(ref HealthHandle);\n        for (int i = 0; i \u003C chunk.Count; i++)\n        {\n            \u002F\u002F Process\n        }\n    }\n}\n\n\u002F\u002F 5. Avoid structural changes in hot paths\n\u002F\u002F Use enableable components instead of add\u002Fremove\npublic struct Disabled : IComponentData, IEnableableComponent { }\n```\n\n## Best Practices\n\n### Do's\n\n- **Use ISystem over SystemBase** - Better performance\n- **Burst compile everything** - Massive speedup\n- **Batch structural changes** - Use ECB\n- **Profile with Profiler** - Identify bottlenecks\n- **Use Aspects** - Clean component grouping\n\n### Don'ts\n\n- **Don't use managed types** - Breaks Burst\n- **Don't structural change in jobs** - Use ECB\n- **Don't over-architect** - Start simple\n- **Don't ignore chunk utilization** - Group similar entities\n- **Don't forget disposal** - Native collections leak\n","# Unity ECS Patterns\n\nProduction patterns for Unity's Data-Oriented Technology Stack (DOTS) including Entity Component System, Job System, and Burst Compiler.\n\n## When to Use This Skill\n\n- Building high-performance Unity games\n- Managing thousands of entities efficiently\n- Implementing data-oriented game systems\n- Optimizing CPU-bound game logic\n- Converting OOP game code to ECS\n- Using Jobs and Burst for parallelization\n\n## Core Concepts\n\n### 1. ECS vs OOP\n\n| Aspect      | Traditional OOP   | ECS\u002FDOTS        |\n| ----------- | ----------------- | --------------- |\n| Data layout | Object-oriented   | Data-oriented   |\n| Memory      | Scattered         | Contiguous      |\n| Processing  | Per-object        | Batched         |\n| Scaling     | Poor with count   | Linear scaling  |\n| Best for    | Complex behaviors | Mass simulation |\n\n### 2. DOTS Components\n\n```\nEntity: Lightweight ID (no data)\nComponent: Pure data (no behavior)\nSystem: Logic that processes components\nWorld: Container for entities\nArchetype: Unique combination of components\nChunk: Memory block for same-archetype entities\n```\n\n## Patterns\n\n### Pattern 1: Basic ECS Setup\n\n```csharp\nusing Unity.Entities;\nusing Unity.Mathematics;\nusing Unity.Transforms;\nusing Unity.Burst;\nusing Unity.Collections;\n\n\u002F\u002F Component: Pure data, no methods\npublic struct Speed : IComponentData\n{\n    public float Value;\n}\n\npublic struct Health : IComponentData\n{\n    public float Current;\n    public float Max;\n}\n\npublic struct Target : IComponentData\n{\n    public Entity Value;\n}\n\n\u002F\u002F Tag component (zero-size marker)\npublic struct EnemyTag : IComponentData { }\npublic struct PlayerTag : IComponentData { }\n\n\u002F\u002F Buffer component (variable-size array)\n[InternalBufferCapacity(8)]\npublic struct InventoryItem : IBufferElementData\n{\n    public int ItemId;\n    public int Quantity;\n}\n\n\u002F\u002F Shared component (grouped entities)\npublic struct TeamId : ISharedComponentData\n{\n    public int Value;\n}\n```\n\n### Pattern 2: Systems with ISystem (Recommended)\n\n```csharp\nusing Unity.Entities;\nusing Unity.Transforms;\nusing Unity.Mathematics;\nusing Unity.Burst;\n\n\u002F\u002F ISystem: Unmanaged, Burst-compatible, highest performance\n[BurstCompile]\npublic partial struct MovementSystem : ISystem\n{\n    [BurstCompile]\n    public void OnCreate(ref SystemState state)\n    {\n        \u002F\u002F Require components before system runs\n        state.RequireForUpdate\u003CSpeed>();\n    }\n\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        float deltaTime = SystemAPI.Time.DeltaTime;\n\n        \u002F\u002F Simple foreach - auto-generates job\n        foreach (var (transform, speed) in\n            SystemAPI.Query\u003CRefRW\u003CLocalTransform>, RefRO\u003CSpeed>>())\n        {\n            transform.ValueRW.Position +=\n                new float3(0, 0, speed.ValueRO.Value * deltaTime);\n        }\n    }\n\n    [BurstCompile]\n    public void OnDestroy(ref SystemState state) { }\n}\n\n\u002F\u002F With explicit job for more control\n[BurstCompile]\npublic partial struct MovementJobSystem : ISystem\n{\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        var job = new MoveJob\n        {\n            DeltaTime = SystemAPI.Time.DeltaTime\n        };\n\n        state.Dependency = job.ScheduleParallel(state.Dependency);\n    }\n}\n\n[BurstCompile]\npublic partial struct MoveJob : IJobEntity\n{\n    public float DeltaTime;\n\n    void Execute(ref LocalTransform transform, in Speed speed)\n    {\n        transform.Position += new float3(0, 0, speed.Value * DeltaTime);\n    }\n}\n```\n\n### Pattern 3: Entity Queries\n\n```csharp\n[BurstCompile]\npublic partial struct QueryExamplesSystem : ISystem\n{\n    private EntityQuery _enemyQuery;\n\n    public void OnCreate(ref SystemState state)\n    {\n        \u002F\u002F Build query manually for complex cases\n        _enemyQuery = new EntityQueryBuilder(Allocator.Temp)\n            .WithAll\u003CEnemyTag, Health, LocalTransform>()\n            .WithNone\u003CDead>()\n            .WithOptions(EntityQueryOptions.FilterWriteGroup)\n            .Build(ref state);\n    }\n\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        \u002F\u002F SystemAPI.Query - simplest approach\n        foreach (var (health, entity) in\n            SystemAPI.Query\u003CRefRW\u003CHealth>>()\n                .WithAll\u003CEnemyTag>()\n                .WithEntityAccess())\n        {\n            if (health.ValueRO.Current \u003C= 0)\n            {\n                \u002F\u002F Mark for destruction\n                SystemAPI.GetSingleton\u003CEndSimulationEntityCommandBufferSystem.Singleton>()\n                    .CreateCommandBuffer(state.WorldUnmanaged)\n                    .DestroyEntity(entity);\n            }\n        }\n\n        \u002F\u002F Get count\n        int enemyCount = _enemyQuery.CalculateEntityCount();\n\n        \u002F\u002F Get all entities\n        var enemies = _enemyQuery.ToEntityArray(Allocator.Temp);\n\n        \u002F\u002F Get component arrays\n        var healths = _enemyQuery.ToComponentDataArray\u003CHealth>(Allocator.Temp);\n    }\n}\n```\n\n### Pattern 4: Entity Command Buffers (Structural Changes)\n\n```csharp\n\u002F\u002F Structural changes (create\u002Fdestroy\u002Fadd\u002Fremove) require command buffers\n[BurstCompile]\n[UpdateInGroup(typeof(SimulationSystemGroup))]\npublic partial struct SpawnSystem : ISystem\n{\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        var ecbSingleton = SystemAPI.GetSingleton\u003CBeginSimulationEntityCommandBufferSystem.Singleton>();\n        var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged);\n\n        foreach (var (spawner, transform) in\n            SystemAPI.Query\u003CRefRW\u003CSpawner>, RefRO\u003CLocalTransform>>())\n        {\n            spawner.ValueRW.Timer -= SystemAPI.Time.DeltaTime;\n\n            if (spawner.ValueRO.Timer \u003C= 0)\n            {\n                spawner.ValueRW.Timer = spawner.ValueRO.Interval;\n\n                \u002F\u002F Create entity (deferred until sync point)\n                Entity newEntity = ecb.Instantiate(spawner.ValueRO.Prefab);\n\n                \u002F\u002F Set component values\n                ecb.SetComponent(newEntity, new LocalTransform\n                {\n                    Position = transform.ValueRO.Position,\n                    Rotation = quaternion.identity,\n                    Scale = 1f\n                });\n\n                \u002F\u002F Add component\n                ecb.AddComponent(newEntity, new Speed { Value = 5f });\n            }\n        }\n    }\n}\n\n\u002F\u002F Parallel ECB usage\n[BurstCompile]\npublic partial struct ParallelSpawnJob : IJobEntity\n{\n    public EntityCommandBuffer.ParallelWriter ECB;\n\n    void Execute([EntityIndexInQuery] int index, in Spawner spawner)\n    {\n        Entity e = ECB.Instantiate(index, spawner.Prefab);\n        ECB.AddComponent(index, e, new Speed { Value = 5f });\n    }\n}\n```\n\n### Pattern 5: Aspect (Grouping Components)\n\n```csharp\nusing Unity.Entities;\nusing Unity.Transforms;\nusing Unity.Mathematics;\n\n\u002F\u002F Aspect: Groups related components for cleaner code\npublic readonly partial struct CharacterAspect : IAspect\n{\n    public readonly Entity Entity;\n\n    private readonly RefRW\u003CLocalTransform> _transform;\n    private readonly RefRO\u003CSpeed> _speed;\n    private readonly RefRW\u003CHealth> _health;\n\n    \u002F\u002F Optional component\n    [Optional]\n    private readonly RefRO\u003CShield> _shield;\n\n    \u002F\u002F Buffer\n    private readonly DynamicBuffer\u003CInventoryItem> _inventory;\n\n    public float3 Position\n    {\n        get => _transform.ValueRO.Position;\n        set => _transform.ValueRW.Position = value;\n    }\n\n    public float CurrentHealth => _health.ValueRO.Current;\n    public float MaxHealth => _health.ValueRO.Max;\n    public float MoveSpeed => _speed.ValueRO.Value;\n\n    public bool HasShield => _shield.IsValid;\n    public float ShieldAmount => HasShield ? _shield.ValueRO.Amount : 0f;\n\n    public void TakeDamage(float amount)\n    {\n        float remaining = amount;\n\n        if (HasShield && _shield.ValueRO.Amount > 0)\n        {\n            \u002F\u002F Shield absorbs damage first\n            remaining = math.max(0, amount - _shield.ValueRO.Amount);\n        }\n\n        _health.ValueRW.Current = math.max(0, _health.ValueRO.Current - remaining);\n    }\n\n    public void Move(float3 direction, float deltaTime)\n    {\n        _transform.ValueRW.Position += direction * _speed.ValueRO.Value * deltaTime;\n    }\n\n    public void AddItem(int itemId, int quantity)\n    {\n        _inventory.Add(new InventoryItem { ItemId = itemId, Quantity = quantity });\n    }\n}\n\n\u002F\u002F Using aspect in system\n[BurstCompile]\npublic partial struct CharacterSystem : ISystem\n{\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        float dt = SystemAPI.Time.DeltaTime;\n\n        foreach (var character in SystemAPI.Query\u003CCharacterAspect>())\n        {\n            character.Move(new float3(1, 0, 0), dt);\n\n            if (character.CurrentHealth \u003C character.MaxHealth * 0.5f)\n            {\n                \u002F\u002F Low health logic\n            }\n        }\n    }\n}\n```\n\n### Pattern 6: Singleton Components\n\n```csharp\n\u002F\u002F Singleton: Exactly one entity with this component\npublic struct GameConfig : IComponentData\n{\n    public float DifficultyMultiplier;\n    public int MaxEnemies;\n    public float SpawnRate;\n}\n\npublic struct GameState : IComponentData\n{\n    public int Score;\n    public int Wave;\n    public float TimeRemaining;\n}\n\n\u002F\u002F Create singleton on world creation\npublic partial struct GameInitSystem : ISystem\n{\n    public void OnCreate(ref SystemState state)\n    {\n        var entity = state.EntityManager.CreateEntity();\n        state.EntityManager.AddComponentData(entity, new GameConfig\n        {\n            DifficultyMultiplier = 1.0f,\n            MaxEnemies = 100,\n            SpawnRate = 2.0f\n        });\n        state.EntityManager.AddComponentData(entity, new GameState\n        {\n            Score = 0,\n            Wave = 1,\n            TimeRemaining = 120f\n        });\n    }\n}\n\n\u002F\u002F Access singleton in system\n[BurstCompile]\npublic partial struct ScoreSystem : ISystem\n{\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        \u002F\u002F Read singleton\n        var config = SystemAPI.GetSingleton\u003CGameConfig>();\n\n        \u002F\u002F Write singleton\n        ref var gameState = ref SystemAPI.GetSingletonRW\u003CGameState>().ValueRW;\n        gameState.TimeRemaining -= SystemAPI.Time.DeltaTime;\n\n        \u002F\u002F Check exists\n        if (SystemAPI.HasSingleton\u003CGameConfig>())\n        {\n            \u002F\u002F ...\n        }\n    }\n}\n```\n\n### Pattern 7: Baking (Converting GameObjects)\n\n```csharp\nusing Unity.Entities;\nusing UnityEngine;\n\n\u002F\u002F Authoring component (MonoBehaviour in Editor)\npublic class EnemyAuthoring : MonoBehaviour\n{\n    public float Speed = 5f;\n    public float Health = 100f;\n    public GameObject ProjectilePrefab;\n\n    class Baker : Baker\u003CEnemyAuthoring>\n    {\n        public override void Bake(EnemyAuthoring authoring)\n        {\n            var entity = GetEntity(TransformUsageFlags.Dynamic);\n\n            AddComponent(entity, new Speed { Value = authoring.Speed });\n            AddComponent(entity, new Health\n            {\n                Current = authoring.Health,\n                Max = authoring.Health\n            });\n            AddComponent(entity, new EnemyTag());\n\n            if (authoring.ProjectilePrefab != null)\n            {\n                AddComponent(entity, new ProjectilePrefab\n                {\n                    Value = GetEntity(authoring.ProjectilePrefab, TransformUsageFlags.Dynamic)\n                });\n            }\n        }\n    }\n}\n\n\u002F\u002F Complex baking with dependencies\npublic class SpawnerAuthoring : MonoBehaviour\n{\n    public GameObject[] Prefabs;\n    public float Interval = 1f;\n\n    class Baker : Baker\u003CSpawnerAuthoring>\n    {\n        public override void Bake(SpawnerAuthoring authoring)\n        {\n            var entity = GetEntity(TransformUsageFlags.Dynamic);\n\n            AddComponent(entity, new Spawner\n            {\n                Interval = authoring.Interval,\n                Timer = 0f\n            });\n\n            \u002F\u002F Bake buffer of prefabs\n            var buffer = AddBuffer\u003CSpawnPrefabElement>(entity);\n            foreach (var prefab in authoring.Prefabs)\n            {\n                buffer.Add(new SpawnPrefabElement\n                {\n                    Prefab = GetEntity(prefab, TransformUsageFlags.Dynamic)\n                });\n            }\n\n            \u002F\u002F Declare dependencies\n            DependsOn(authoring.Prefabs);\n        }\n    }\n}\n```\n\n### Pattern 8: Jobs with Native Collections\n\n```csharp\nusing Unity.Jobs;\nusing Unity.Collections;\nusing Unity.Burst;\nusing Unity.Mathematics;\n\n[BurstCompile]\npublic struct SpatialHashJob : IJobParallelFor\n{\n    [ReadOnly]\n    public NativeArray\u003Cfloat3> Positions;\n\n    \u002F\u002F Thread-safe write to hash map\n    public NativeParallelMultiHashMap\u003Cint, int>.ParallelWriter HashMap;\n\n    public float CellSize;\n\n    public void Execute(int index)\n    {\n        float3 pos = Positions[index];\n        int hash = GetHash(pos);\n        HashMap.Add(hash, index);\n    }\n\n    int GetHash(float3 pos)\n    {\n        int x = (int)math.floor(pos.x \u002F CellSize);\n        int y = (int)math.floor(pos.y \u002F CellSize);\n        int z = (int)math.floor(pos.z \u002F CellSize);\n        return x * 73856093 ^ y * 19349663 ^ z * 83492791;\n    }\n}\n\n[BurstCompile]\npublic partial struct SpatialHashSystem : ISystem\n{\n    private NativeParallelMultiHashMap\u003Cint, int> _hashMap;\n\n    public void OnCreate(ref SystemState state)\n    {\n        _hashMap = new NativeParallelMultiHashMap\u003Cint, int>(10000, Allocator.Persistent);\n    }\n\n    public void OnDestroy(ref SystemState state)\n    {\n        _hashMap.Dispose();\n    }\n\n    [BurstCompile]\n    public void OnUpdate(ref SystemState state)\n    {\n        var query = SystemAPI.QueryBuilder()\n            .WithAll\u003CLocalTransform>()\n            .Build();\n\n        int count = query.CalculateEntityCount();\n\n        \u002F\u002F Resize if needed\n        if (_hashMap.Capacity \u003C count)\n        {\n            _hashMap.Capacity = count * 2;\n        }\n\n        _hashMap.Clear();\n\n        \u002F\u002F Get positions\n        var positions = query.ToComponentDataArray\u003CLocalTransform>(Allocator.TempJob);\n        var posFloat3 = new NativeArray\u003Cfloat3>(count, Allocator.TempJob);\n\n        for (int i = 0; i \u003C count; i++)\n        {\n            posFloat3[i] = positions[i].Position;\n        }\n\n        \u002F\u002F Build hash map\n        var hashJob = new SpatialHashJob\n        {\n            Positions = posFloat3,\n            HashMap = _hashMap.AsParallelWriter(),\n            CellSize = 10f\n        };\n\n        state.Dependency = hashJob.Schedule(count, 64, state.Dependency);\n\n        \u002F\u002F Cleanup\n        positions.Dispose(state.Dependency);\n        posFloat3.Dispose(state.Dependency);\n    }\n}\n```\n\n## Performance Tips\n\n```csharp\n\u002F\u002F 1. Use Burst everywhere\n[BurstCompile]\npublic partial struct MySystem : ISystem { }\n\n\u002F\u002F 2. Prefer IJobEntity over manual iteration\n[BurstCompile]\npartial struct OptimizedJob : IJobEntity\n{\n    void Execute(ref LocalTransform transform) { }\n}\n\n\u002F\u002F 3. Schedule parallel when possible\nstate.Dependency = job.ScheduleParallel(state.Dependency);\n\n\u002F\u002F 4. Use ScheduleParallel with chunk iteration\n[BurstCompile]\npartial struct ChunkJob : IJobChunk\n{\n    public ComponentTypeHandle\u003CHealth> HealthHandle;\n\n    public void Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex,\n        bool useEnabledMask, in v128 chunkEnabledMask)\n    {\n        var healths = chunk.GetNativeArray(ref HealthHandle);\n        for (int i = 0; i \u003C chunk.Count; i++)\n        {\n            \u002F\u002F Process\n        }\n    }\n}\n\n\u002F\u002F 5. Avoid structural changes in hot paths\n\u002F\u002F Use enableable components instead of add\u002Fremove\npublic struct Disabled : IComponentData, IEnableableComponent { }\n```\n\n## Best Practices\n\n### Do's\n\n- **Use ISystem over SystemBase** - Better performance\n- **Burst compile everything** - Massive speedup\n- **Batch structural changes** - Use ECB\n- **Profile with Profiler** - Identify bottlenecks\n- **Use Aspects** - Clean component grouping\n\n### Don'ts\n\n- **Don't use managed types** - Breaks Burst\n- **Don't structural change in jobs** - Use ECB\n- **Don't over-architect** - Start simple\n- **Don't ignore chunk utilization** - Group similar entities\n- **Don't forget disposal** - Native collections leak\n",{"name":5,"description":7},"main","900bb95bbe72cdb94af6f5a620aa5081264b7b6d",".claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fgame-development\u002Fskills\u002Funity-ecs-patterns",0,"https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up#readme","https:\u002F\u002Fgithub.com\u002Fsteph-frtech","2026-05-16 00:03:30",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add steph-frtech\u002Fclaude-code-up --skill unity-ecs-patterns",{"tool":37,"command":38},"bunx","bunx skills add steph-frtech\u002Fclaude-code-up --skill unity-ecs-patterns",{"tool":40,"command":41},"pnpm","pnpm dlx skills add steph-frtech\u002Fclaude-code-up --skill unity-ecs-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fgame-development\u002Fskills\u002Funity-ecs-patterns\u002FSKILL.md",true,[],[46,53,60,67,74,81],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":18},"01M72Y1BY6X8TX3DS19Y04NEBQ","example","One-line summary of what this skill does","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002Fskills\u002Fexample\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":18},"01M72Y1A38EYR8S9P1MBYDAQTW","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__writing-plans\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":18},"01M72Y174QSV1B5NV1E4KWHQBR","using-git-worktrees","Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__using-git-worktrees\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M72Y14SQRHHMKG316HGB2CGK","test-driven-development","Use when implementing any feature or bugfix, before writing implementation code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__test-driven-development\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":18},"01M72Y127BCPRH3BRKPJC3Q3G2","systematic-debugging","Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__systematic-debugging\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":18},"01M72Y1090GJA6B67KPD60WPHH","subagent-driven-development","Use when executing implementation plans with independent tasks in the current session","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__subagent-driven-development\u002FSKILL.md",[],[]]