Unity csharp

From j4flmao/agent-skills · View interactive version

Unity csharp is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about Unity DOTS, Unity ECS with Entities, ISystem, IJobEntity, Burst jobs, the C# Job System, NativeArray or GC-free Unity C#. Produces Entities, Jobs and Burst code with correct safety rules. Not for general Unity project architecture (use unity) or engine-agnostic ECS desig

How to use this skill

Skill file

Unity Data-Oriented Technology Stack (DOTS) & C# Mechanics

Purpose

This skill covers Unity's data-oriented stack (ECS, Job System, Burst) and the C# practices that make Unity code fast and correct.

Agent Protocol

Trigger

"unity dots", "unity ecs", "unity entities", "ISystem", "IJobEntity", "burst compiler", "unity job system", "unity c# performance".

Input Context

Output Artifact

C# systems/jobs and authoring code. No file unless requested.

Response Format

Unity: {version}  Entities: {version}
System: {name, query, read/write}
Code: {snippet}
Verify: {Profiler / Burst inspector / Entities hierarchy}

1. Why DOTS: The OOP-Based Entry Points

Unity's classic MonoBehaviour model is object-oriented: each Behaviour instance owns its fields, script lifecycle callbacks run per frame, and objects reference each other. For 10k+ entities, per-object Update() incurs:

DOTS replaces this with contiguous data and systems-in-a-loop.

2. ECS Model in Unity

Packages: Entities 1.x on Unity 6.0-6.3 (com.unity.entities from the Package Manager); from Unity 6.4 Entities, Collections and Mathematics ship as core packages whose version matches the Editor. Code below uses the current ISystem + SystemAPI style (SystemBase Entities.ForEach lambdas are obsolete since Entities 1.4).

2.1 Entities, Components, Systems

// Component: struct, blittable, data-only
public struct Velocity : IComponentData {
    public float3 Linear;
    public float Angular;
}

// System: logic over queries
[BurstCompile]
public partial struct MoveSystem : ISystem {
    [BurstCompile]
    public void OnUpdate(ref SystemState state) {
        var dt = SystemAPI.Time.DeltaTime;
        foreach (var (tf, v) in SystemAPI.Query<RefRW<LocalTransform>, RefRO<Velocity>>()) {
            tf.ValueRW.Position += v.ValueRO.Linear * dt;
        }
    }
}

2.2 Archetypes & Chunks (Storage)

Chunk 0 [Archetype: LocalTransform+Velocity ]
  Transform array: | t0 | t1 | t2 | ... | (contiguous)
  Velocity  array: | v0 | v1 | v2 | ... | (contiguous)

2.3 Structural Changes (Command Buffers)

Adding/removing components moves the entity to another archetype (memcpy of affected fields). Doing this mid-iteration invalidates chunk iteration → use EntityCommandBuffer:

EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.Temp);
// queue AddComponent / SetComponent / DestroyEntity
ecb.Playback(state.EntityManager);

Rules: never call EntityManager.AddComponent inside ScheduleParallel jobs; always buffer.

3. The C# Job System

3.1 IJobEntity / IJobChunk

[BurstCompile]
public partial struct DamageJob : IJobEntity {
    public float Damage;
    void Execute(ref Health health) { health.Value -= Damage; }
}

var handle = new DamageJob { Damage = 5f }.Schedule(state.Dependency);
state.Dependency = handle;   // chain dependencies

3.2 ParallelFor

// IJobEntity: chunks are distributed across worker threads
state.Dependency = new DamageJob { Damage = 5f }.ScheduleParallel(state.Dependency);

4. Burst Compiler

4.1 Burst-Compatible Data Types

| Use | Avoid |

|-----|-------|

| float3/float4x4/quaternion (Unity.Mathematics) — map to SIMD-friendly code | Vector3/Matrix4x4 in hot jobs (supported, but less vectorisation-friendly) |

| NativeArray<T>, NativeList<T>, NativeHashMap | List<T>, Dictionary<K,V> |

| int4/uint4 | System.Numerics types |

| FixedString64Bytes etc. | string, managed exceptions as control flow |

5. C# Patterns for Game Code (Non-DOTS)

5.1 Avoiding Allocation Churn (GC Spikes)

Unity's managed GC pauses frames. Hot-path rules:

5.2 Value Types for Gameplay State

public struct PlayerState { public int Id; public float Hp; public float2 Pos; public int TeamId; }

5.3 Async / Await Patterns

// Unity 6: Awaitable is Unity's allocation-light Task replacement
async Awaitable<string> FetchAsync(string url, CancellationToken ct) {
    using var req = UnityWebRequest.Get(url);
    await req.SendWebRequest();                 // AsyncOperation is awaitable (2023.1+)
    ct.ThrowIfCancellationRequested();
    if (req.result != UnityWebRequest.Result.Success)
        throw new IOException($"GET {url} failed: {req.error}");
    return req.downloadHandler.text;            // continuation runs on the main thread
}

5.4 Singletons & Service Locators

public sealed class GameManager : MonoBehaviour {
    public static GameManager I { get; private set; }
    void Awake() {
        if (I != null && I != this) { Destroy(gameObject); return; }   // keep the first instance
        I = this;
    }
    void OnDestroy() { if (I == this) I = null; }
}

6. Serialization & Persistence

7. Compilation & asmdef

8. Profiling C#

9. C# Best-Practice Cheat Sheet

| Rule | Why |

|------|-----|

| Prefer TryGetComponent over GetComponent + null check | no Editor-only allocation when the component is missing |

| Cache component references in Awake | repeated GetComponent calls are lookups every time |

| Begin/End sample with profiler markers | measure before optimizing |

| Pre-allocate everything once | cache and pool |

| Avoid FindObjectOfType (obsolete since 2023.1; use FindAnyObjectByType only outside hot paths) | scans the scene; expensive |

| Prefer fixed-point for sync systems | determinism across devices |

10. Decision: DOTS vs MonoBehaviour

| Criterion | DOTS/ECS+Jobs | MonoBehaviour |

|-----------|---------------|---------------|

| 100k entities / massive crowds | Strong | Poor |

| Rapid UI/prototype | Poor | Excellent |

| Deep gameplay narrative logic | More setup | Natural |

| Physics | Unity Physics / Havok Physics for Unity packages | Built-in PhysX |

| Shader/instancing synergy | GPU-instancing friendly | Manual |

Rule: mix intelligently — DOTS for the simulation hot-path, MonoBehaviours for the editors/design-facing layers.

11. References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.