[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7FD0VB4B7KBG1N1Q6PD8EJB":3,"skill-same:01M7FD0VB4B7KBG1N1Q6PD8EJB":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7FD0VB4B7KBG1N1Q6PD8EJB","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.","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Funity-ecs-patterns\u002FSKILL.md",[],[],"2026-11-16 10:05:34",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","d69096e239f2a89aabc2cd078c47664a9d3b1e11","06-前端与设计\u002Funity-ecs-patterns",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill unity-ecs-patterns",{"tool":38,"command":39},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill unity-ecs-patterns",{"tool":41,"command":42},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill unity-ecs-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Funity-ecs-patterns\u002FSKILL.md",true,[],[47,54,59,66,73,80],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],{"skillNo":55,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]