Unity

From j4flmao/agent-skills · View interactive version

Unity is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about Unity 6, MonoBehaviour, the player loop, URP, HDRP, Addressables, Netcode for GameObjects, Unity physics or Unity Profiler. Produces Unity project architecture, gameplay code and performance fixes. Not for DOTS, Entities and Burst in depth (use unity-csharp) or Unreal (u

How to use this skill

Skill file

Unity Deep Engineering Guide

Purpose

Unity is a component-based game engine built around GameObjects, MonoBehaviours, and a C# scripting layer. Modern Unity adds Data-Oriented Technology Stack (DOTS/E.C.S.) and two Scriptable Render Pipelines (URP/HDRP). This guide covers how a lead engineer thinks about Unity: architecture, C# performance, data-oriented design, rendering, physics, multiplayer, and profiling.

Agent Protocol

Trigger

"unity", "unity 6", "monobehaviour", "URP", "HDRP", "addressables", "unity performance", "netcode for gameobjects".

Input Context

Output Artifact

C# code, project/pipeline settings or a performance plan. No file unless requested.

Response Format

Unity: {6.x}  Pipeline: {URP | HDRP}
Change: {what and why}
Code: {snippet}
Verify: {Profiler / Frame Debugger result}

1. Engine Architecture

Unity Player/Editor
  Application      (UnityEngine)
    SceneManager   -> load/unload Scenes (additive)
      GameObject   (identity + transform)
        Component  (MonoBehaviour, Renderer, Collider, Animator...)
    PlayerLoop:    (fixed update order, engine-driven)
      PlayerLoop.SetPlayerLoop -> custom systems injected
    Module systems: Physics (PhysX/Box2D), Audio (FMOD), UI (UGUI/UI Toolkit),
                    Rendering (URP/HDRP/Built-in), Input (new Input System)

1.1 The Player Loop & Update Order

Within one frame Unity calls systems in a fixed order:

void Update()   // per rendered frame
void FixedUpdate() // fixed timestep: physics, network ticks (default 0.02s)
void LateUpdate()  // camera follow, post-movement

Rules:

1.2 Multiple Scenes (Additive Loading)

2. GameObject & Component Model

public class Health : MonoBehaviour {
    public int maxHp = 100;
    int current;

    void OnEnable()  { /* add self to manager lists */ }
    void OnDisable() { /* remove self */ }
}

2.1 GetComponent Performance

GetComponent<T>() per frame per object is a hot-path mistake:

2.2 FindFirstObjectByType / GameObject.Find

FindObjectOfType is deprecated (2023.1+) in favour of FindFirstObjectByType / FindAnyObjectByType. All of these scan the scene. They MUST not run on the per-frame path. For singletons, register in Awake, destroy in OnDestroy:

public static GameManager I;  // global accessor
void Awake() { I = this; }
void OnDestroy() { if (I == this) I = null; }

3. The DOTS / ECS Stack

Unity DOTS replaces MonoBehaviours with archetype-based ECS:

// Component - plain struct, no MonoBehaviour
public struct Velocity : IComponentData { public float3 Value; }

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

When to use DOTS vs classic GameObjects

| Need | Path |

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

| 1000s of agents, bullets, particles | DOTS/ECS + Burst + Jobs |

| Rapid prototyping / small games | Classic GameObject/MonoBehaviours |

| UI, gameplay narrative, inventory | Classic (UGUI) |

| Massive open world streaming | DOTS SubScene streaming |

4. Rendering Pipelines

4.1 Choose the Pipeline

| Pipeline | Use |

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

| Built-in | Legacy, quick prototypes, simple mobile games |

| URP | Default for most new projects (mobile to PC/console); Forward, Forward+ or Deferred paths |

| HDRP | Film-grade lighting: deferred, ray tracing, volumetrics, high-end PC/console |

| Custom SRP | Only with a dedicated rendering team; URP/HDRP passes are extended via Render Graph (ScriptableRenderPass.RecordRenderGraph, Unity 6) |

4.2 URP vs HDRP in practice

4.3 Draw Call Reduction

  1. SRP Batcher (on by default in URP/HDRP) — cuts CPU cost per draw for materials using the same shader variant; keep shaders SRP-Batcher compatible (per-material CBUFFER).
  2. GPU Resident Drawer (Unity 6, BatchRendererGroup-based) or GPU instancing via Graphics.RenderMeshInstanced for many repeated meshes (vegetation, crowds).
  3. Static batching: mark static → combined at build.
  4. Minimize material variants (KeywordEnum, MaterialPropertyBlock for per-object color).
  5. Bake lighting (Lightmapping) instead of dynamic.

4.4 Shader Lab & Shader Graph

5. Physics

6. Animation & Timing

7. UI (UGUI / UI Toolkit / IMGUI)

8. Asset Pipeline

8.1 Addressables

Addressables = load by key, async, memory-managed:

// Instantiate + track in one call; release the instance, not the prefab
var handle = Addressables.InstantiateAsync("enemies/wolf", spawnPoint.position, Quaternion.identity);
GameObject wolf = await handle.Task;
// ... later
Addressables.ReleaseInstance(wolf);

// Or load once, instantiate many, release the load handle when done
var prefabHandle = Addressables.LoadAssetAsync<GameObject>("enemies/wolf");
GameObject prefab = await prefabHandle.Task;
// Instantiate(prefab) ... destroy instances normally ...
Addressables.Release(prefabHandle);

8.2 Streaming & Background Loading

9. Multiplayer (Netcode for GameObjects / Netcode Transport / UnityTransport)

10. Performance Rules (Lead Level)

  1. Profile first: Unity Profiler + Burst metrics; GPU profiler (RenderDoc, GPUView).
  2. ExecuteInEditMode scripts only where needed; keep editor-only work in #if UNITY_EDITOR.
  3. Avoid transform.position in a loop (accessing Transform is cheap-ish, but allocations from Find/GetComponentsInChildren are not).
  4. Garbage: minimize per-frame allocations; cache arrays; use NativeArray/NativeList in jobs.
  5. Broke update: use FixedUpdate only for physics; game logic in Update.
  6. Root motion vs scripted movement: profile Animator cost.
  7. Camera.main is cached internally since 2020.2, but still store camera references in fields rather than looking them up everywhere.

10.1 Frame Budget Table Template

| System | Budget (ms) @ 60fps |

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

| Simulation (Update) | 2.0 |

| Physics (Fixed) | 2.0 |

| Animation | 2.0 |

| AI / NavMesh | 1.5 |

| Rendering (CPU submit) | 3.0 |

| Rendering (GPU) | 8.3–14.0 |

| UI | 1.0 |

| Netcode | 1.0 |

| Misc / Driver | 2.0 |

Total must fit in 16.6ms (or 1000/refresh).

11. Project Structure Convention

Assets/
  Scripts/         # namespaces by system
  Scenes/
  Prefabs/
  Addressables/    # addressable groups
  Materials/
  Textures/
  Audio/
  _BuildTools/     # editor scripts, CI
  .gitignore: Library/ Temp/ Logs/ UserSettings/

Use .asmdef (assembly definition) per folder to speed up compile times and control references.

12. Anti-Patterns

| Anti-pattern | Consequence | Fix |

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

| FindFirstObjectByType/GameObject.Find in Update | full scene scan | cache in Awake or register with a manager |

| Rigidbody move in Update | physics jitter | MovePosition/forces in FixedUpdate + Rigidbody interpolation |

| Per-frame allocations (strings) | GC pauses | string builders, pooling |

| Resources.Load in loop | load spikes | Addressables + cache |

| One Canvas for everything | layout rebuild | split by update frequency |

| Private state not serialized | inspector values lost | [SerializeField] private fields |

| Not using .asmdef | long compile | per-system asmdefs |

| Physics without layer matrix | wasted contacts | IgnoreLayerCollision |

13. When to NOT Use Unity

14. 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.