Unity Design System
Use this skill to turn a Unity project into a maintainable design system: clear authoring data,
explicit runtime state, small domain modules, deterministic startup, typed events, focused services,
and editor-safe content workflows.
Prefer patterns that fit Unity's inspector and scene workflow without hiding dependencies behind
global state. Treat every large MonoBehaviour or service as a liability until its responsibilities
are visible and bounded.
Workflow
- Inspect local instructions, project structure, service/bootstrap entry points, representative
domain modules, UI screens, save/reset code, and tests.
- Separate observed patterns into:
- Standards to keep: repeatable patterns that reduce coupling or improve authoring safety.
- Patterns to repair: repeated smells that increase runtime risk or maintenance cost.
- If implementing, change the smallest slice that establishes the standard. Do not redesign every
domain at once.
- Validate with focused tests for plain C# logic, Unity editor tests where needed, and a scene/play
smoke check for lifecycle or UI changes.
Core Standards
- Use
ScriptableObject for authoring data and content definitions.
- Keep runtime state in runtime objects, services, scene instances, or save payloads, not shared assets.
- Split each game domain by reason to change: data, events, interfaces, pure logic, save data,
authoring assets, and service orchestration.
- Keep services as orchestration boundaries. Put calculations, validation, matching, and state
transitions in plain C# classes.
- Use typed events for cross-system notifications and UI updates, not for opaque command chains.
- Make required dependencies visible through serialized references, constructors, or one composition
root. Treat missing required dependencies as startup errors.
- Flag any MonoBehaviour or service over 200 LOC, or any class with more than 5 public methods, for
extraction unless there is a clear Unity lifecycle reason.
- Prefer deletion over speculative abstraction. Add interfaces only when variants share a real
lifecycle.
Domain Module Template
For gameplay domains such as brewing, inventory, economy, customer, recipe, audio, progression,
processing, combat, cards, enemies, or reset, prefer this shape:
Scripts/<Domain>/
├── Data/ # Enums, IDs, small value types
├── Events/ # Typed event structs for requests and notifications
├── Interface/ # Narrow provider/service interfaces
├── Logic/ # Pure rules, validators, matchers, registries, calculators
├── SaveData/ # Serializable save payloads and reset category metadata
├── ScriptableObjects/ # Authoring data and config assets
└── Service/ # Unity lifecycle adapter and orchestration boundary
Rules:
- Do not force empty folders for tiny domains, but use the same mental split.
- Domain event files should be easy to find; do not hide public event structs at the bottom of UI
or scene controller files.
- Service methods should read like orchestration: validate, update runtime object, publish events,
call save, update optional presentation hooks.
Authoring Data
Use ScriptableObject assets for ingredients, recipes, cards, actions, enemies, processing stations,
shop upgrades, audio clips, scenes, difficulty, tutorial pages, boss definitions, and config values.
Rules:
- Asset classes expose mostly read-only properties.
- Asset classes do not mutate per-run state.
- Use
[CreateAssetMenu], [Header], [Tooltip], [Range], and OnValidate to make authoring safe.
- Store stable content IDs on definitions; use runtime IDs for spawned instances.
- Prefer explicit serialized references for required config over scattered
Resources.Load strings.
Good shape:
public sealed class IngredientData : ScriptableObject
{
[SerializeField] private IngredientId id;
[SerializeField] private string displayName;
[SerializeField] private MaterialEffectProfile effectProfile;
public IngredientId Id => id;
public string DisplayName => displayName;
public MaterialEffectProfile EffectProfile => effectProfile;
private void OnValidate()
{
if (id == IngredientId.None)
Debug.LogWarning($"[{nameof(IngredientData)}] {name} has no id.");
}
}
Runtime State
Create runtime wrappers for stateful gameplay concepts such as active brew sessions, customer queues,
card stacks, cooldowns, EX state, current health, active modifiers, selected phase, and spawned enemy
handles.
Rules:
- A
ScriptableObject should not own fields like IsActive, IsEx, CooldownTimer, current stack
count, current HP, or active scene references.
- Runtime data can reference its definition, but the definition should not reference runtime state.
- Reset runtime state through constructors, explicit reset services, or reset orchestrators.
- Plain runtime classes should be testable without loading scenes.
Good shape:
public sealed class BrewSession
{
private readonly RawBrewTotals totals = new();
public BrewingPhase Phase { get; private set; } = BrewingPhase.NoIngredient;
public MaterialEffectProfile RawProfile => totals.TotalProfile;
public bool TryAddMaterial(ProcessedMaterial material)
{
if (Phase != BrewingPhase.NoIngredient)
return false;
return totals.TryAdd(material);
}
}
Pure Logic First
Put deterministic rules in plain C# classes or structs:
- Validators:
ValidateAddMaterial, ValidateStartBrew, ValidatePlacement.
- Calculators: price, quality, score, XP, cooldown.
- Matchers: customer request match, recipe match, target selection.
- State helpers: stabilizers, phase transition rules, runtime statistics.
- Registries: maps from stable IDs to authoring assets.
Rules:
- Keep Unity side effects out of rule code unless the rule is intrinsically visual or physics-bound.
- Return structured results, not just booleans, when UI/debug needs failure reasons.
- Write focused NUnit tests for these classes before adding scene-level tests.
Services And Bootstrap
Use one composition root to instantiate persistent services, register them, load persistent scenes,
then initialize services in deterministic order.
Rules:
- A service may own runtime state and coordinate side effects, but should not contain every business
rule for the domain.
- Keep
ServiceLocator calls near composition roots, UI adapters, and service boundaries. Avoid
ServiceLocator.Get<T>() inside plain logic, modifiers, or data objects.
- Prefer interfaces for provider contracts when consumers only need a small surface.
- Provide explicit initialization priorities only when order matters.
- Unregister or clear static service registries during teardown or test reset.
- Missing required services should fail fast. Optional polish dependencies can be nullable.
Service shape:
public sealed class BrewingService : InitializableServiceBase<BrewingService>, IBrewingProvider
{
private BrewingSession session;
public override Task Initialize()
{
session = new BrewingSession();
EventBus.Subscribe<RequestStartBrewEvent>(OnStartRequested);
return Task.CompletedTask;
}
protected override void OnDestroy()
{
EventBus.Unsubscribe<RequestStartBrewEvent>(OnStartRequested);
base.OnDestroy();
}
}
Event System
Use typed event structs for broad notifications such as phase changes, UI readiness, item usage,
achievement unlocks, score changes, combat transitions, save/reset progress, and service readiness.
Rules:
- Subscribe in
OnEnable/Initialize; unsubscribe in the paired lifecycle method.
- Use request events for user/system intent and result events for state changes.
- Keep event definitions in domain event files.
- Avoid duplicated event names in different scopes unless there is a namespace-level reason.
- Avoid chains where event A publishes B publishes C without one workflow owner.
- Event bus debugging should expose subscriber counts and recent publish history.
- Isolate subscriber exceptions if a failure in one listener should not block the rest.
UI System
UI renders state, publishes intent, and delegates rules to services or pure logic.
Rules:
- Use reusable UI base components only for repeated mechanics: show/hide, modal pause, tabs,
carousel, buttons, drag zones, effect displays.
- Split large screens into presenters/controllers for pagination, action buttons, effect previews,
drop zones, animation, and service adapters.
- UI may cache services on enter/awake, but it should prefer provider interfaces when possible.
- If UI registers as a visual provider, it must unregister on close/exit/disable.
- Use a reference-counted pause manager for modal UI.
- Avoid
GameObject.Find, tag lookup, and Camera.main in frequently used UI paths.
Save And Reset
Centralize persistence behind generic save payloads and explicit reset orchestration.
Rules:
- Every save payload derives from a base save type with explicit filename and reset policy.
- Async save/load returns
Task. Reserve async void for Unity event entrypoints only.
- Do not fire-and-forget important saves during reset, scene changes, or quit flows.
- Separate platform IO, serialization, encryption/obfuscation, registry, and reset selection if the
save manager grows large.
- Reset should delete matching save payloads, reset in-memory services by priority, and publish
progress/completion events.
- Treat hardcoded keys and fixed IVs as obfuscation only; do not describe them as strong security.
Editor Tooling
Build small editor tools for repetitive production tasks:
- Event bus debugger.
- Service/bootstrap debugger.
- Bootstrap inspector with testing overrides.
- Selective save reset tools.
- Asset generators and validators for catalogs, recipes, cutscenes, scenes, audio, or content IDs.
Rules:
- Put editor-only code under
Editor/ or wrap it in #if UNITY_EDITOR.
- Validate selected assets before generating output.
- Make generated folders deterministic and safe to overwrite only after confirmation.
Anti-Patterns To Fix
God MonoBehaviours Or Services
Smell:
- One class handles input, pagination, state restore, service lookups, animation, audio, VFX,
validation, saving, debug, and business rules.
Fix:
- Extract validators, presenters, factories, runtime state objects, and side-effect services.
- Keep MonoBehaviours as Unity adapters/orchestrators.
Hidden Global Dependencies
Smell:
- Frequent
ServiceLocator.Get<T>(), .Instance, FindObjectOfType, FindAnyObjectByType,
GameObject.Find, FindGameObjectWithTag, or Camera.main inside gameplay logic.
Fix:
- Wire dependencies at bootstrap, through serialized fields, or constructors.
- Use interfaces for plain C# services and pass them through constructors.
- Cache optional lookups once at initialization.
Static Lifecycle Leaks
Smell:
- Static service/event registries have no unregister or test reset path.
- Services keep references to destroyed scene UI or visual providers.
Fix:
- Add explicit
Unregister, ClearAll, or test teardown paths.
- Pair every register/subscribe with unregister/unsubscribe.
- Prefer weak/event ownership only when the lifecycle is genuinely shared.
Event Spaghetti
Smell:
- Events are used as internal method calls, commands have no owner, or behavior requires tracing many
publish/subscribe hops.
Fix:
- Use one orchestrator per workflow.
- Use events for notifications and UI updates.
- Keep request/result event pairs explicit.
Resources.Load Drift
Smell:
- Config and content dependencies are loaded through scattered string paths.
Fix:
- Prefer serialized config references in bootstrap assets or service prefabs.
- If
Resources.LoadAll is used for catalogs, keep paths centralized in one registry and validate
loaded assets.
Async Fire-And-Forget
Smell:
- Important saves, resets, or scene transitions are hidden behind
async void.
Fix:
- Return
Task from service APIs and await at workflow boundaries.
- Keep
async void only at Unity event entrypoints, with local exception handling.
Soft Failure For Required Wiring
Smell:
- Required dependencies log a warning and continue with permissive behavior.
Fix:
- Validate required references in
Awake/OnValidate.
- Disable the component or throw a clear startup error when required wiring is absent.
Duplicate Or Ambiguous Types
Smell:
- Two event structs/classes share the same name in different scopes without clear namespacing.
Fix:
- Use domain-prefixed names such as
SettingsOpenRequestedEvent or place all related events in one
namespace/file.
Half-Built Abstractions
Smell:
- Interfaces or enum branches exist but implementations are empty or no-op.
Fix:
- Delete unused abstraction until needed, or complete behavior with focused tests/demo scene.
Review Checklist
Output Style
When asked to review a Unity codebase, lead with findings ordered by risk. Include file references,
why each pattern matters, and the smallest repair path. When asked to implement a design system,
make the standard real in one representative domain first, then leave a repeatable template for the
next domains.
1---2name: unity-design-system3description: >4 Use when designing, implementing, reviewing, or refactoring Unity game architecture and reusable5 gameplay/UI systems. Trigger on Unity design system, Unity architecture, ScriptableObject6 architecture, data-driven gameplay, EventBus, ServiceLocator, bootstrap, domain module layout,7 phase/state machines, save/load, reset flows, editor tooling, runtime state safety, god object8 cleanup, or requests to identify good/bad Unity codebase patterns and turn them into maintainable9 standards.10metadata:11 source: https://skillmd.com/skills/fauzanazz/unity-design-system12---1314# Unity Design System1516Use this skill to turn a Unity project into a maintainable design system: clear authoring data,17explicit runtime state, small domain modules, deterministic startup, typed events, focused services,18and editor-safe content workflows.1920Prefer patterns that fit Unity's inspector and scene workflow without hiding dependencies behind21global state. Treat every large MonoBehaviour or service as a liability until its responsibilities22are visible and bounded.2324## Workflow25261. Inspect local instructions, project structure, service/bootstrap entry points, representative27 domain modules, UI screens, save/reset code, and tests.282. Separate observed patterns into:29 - **Standards to keep**: repeatable patterns that reduce coupling or improve authoring safety.30 - **Patterns to repair**: repeated smells that increase runtime risk or maintenance cost.313. If implementing, change the smallest slice that establishes the standard. Do not redesign every32 domain at once.334. Validate with focused tests for plain C# logic, Unity editor tests where needed, and a scene/play34 smoke check for lifecycle or UI changes.3536## Core Standards3738- Use `ScriptableObject` for authoring data and content definitions.39- Keep runtime state in runtime objects, services, scene instances, or save payloads, not shared assets.40- Split each game domain by reason to change: data, events, interfaces, pure logic, save data,41 authoring assets, and service orchestration.42- Keep services as orchestration boundaries. Put calculations, validation, matching, and state43 transitions in plain C# classes.44- Use typed events for cross-system notifications and UI updates, not for opaque command chains.45- Make required dependencies visible through serialized references, constructors, or one composition46 root. Treat missing required dependencies as startup errors.47- Flag any MonoBehaviour or service over 200 LOC, or any class with more than 5 public methods, for48 extraction unless there is a clear Unity lifecycle reason.49- Prefer deletion over speculative abstraction. Add interfaces only when variants share a real50 lifecycle.5152## Domain Module Template5354For gameplay domains such as brewing, inventory, economy, customer, recipe, audio, progression,55processing, combat, cards, enemies, or reset, prefer this shape:5657```text58Scripts/<Domain>/59├── Data/ # Enums, IDs, small value types60├── Events/ # Typed event structs for requests and notifications61├── Interface/ # Narrow provider/service interfaces62├── Logic/ # Pure rules, validators, matchers, registries, calculators63├── SaveData/ # Serializable save payloads and reset category metadata64├── ScriptableObjects/ # Authoring data and config assets65└── Service/ # Unity lifecycle adapter and orchestration boundary66```6768Rules:69- Do not force empty folders for tiny domains, but use the same mental split.70- Domain event files should be easy to find; do not hide public event structs at the bottom of UI71 or scene controller files.72- Service methods should read like orchestration: validate, update runtime object, publish events,73 call save, update optional presentation hooks.7475## Authoring Data7677Use `ScriptableObject` assets for ingredients, recipes, cards, actions, enemies, processing stations,78shop upgrades, audio clips, scenes, difficulty, tutorial pages, boss definitions, and config values.7980Rules:81- Asset classes expose mostly read-only properties.82- Asset classes do not mutate per-run state.83- Use `[CreateAssetMenu]`, `[Header]`, `[Tooltip]`, `[Range]`, and `OnValidate` to make authoring safe.84- Store stable content IDs on definitions; use runtime IDs for spawned instances.85- Prefer explicit serialized references for required config over scattered `Resources.Load` strings.8687Good shape:8889```csharp90public sealed class IngredientData : ScriptableObject91{92 [SerializeField] private IngredientId id;93 [SerializeField] private string displayName;94 [SerializeField] private MaterialEffectProfile effectProfile;9596 public IngredientId Id => id;97 public string DisplayName => displayName;98 public MaterialEffectProfile EffectProfile => effectProfile;99100 private void OnValidate()101 {102 if (id == IngredientId.None)103 Debug.LogWarning($"[{nameof(IngredientData)}] {name} has no id.");104 }105}106```107108## Runtime State109110Create runtime wrappers for stateful gameplay concepts such as active brew sessions, customer queues,111card stacks, cooldowns, EX state, current health, active modifiers, selected phase, and spawned enemy112handles.113114Rules:115- A `ScriptableObject` should not own fields like `IsActive`, `IsEx`, `CooldownTimer`, current stack116 count, current HP, or active scene references.117- Runtime data can reference its definition, but the definition should not reference runtime state.118- Reset runtime state through constructors, explicit reset services, or reset orchestrators.119- Plain runtime classes should be testable without loading scenes.120121Good shape:122123```csharp124public sealed class BrewSession125{126 private readonly RawBrewTotals totals = new();127128 public BrewingPhase Phase { get; private set; } = BrewingPhase.NoIngredient;129 public MaterialEffectProfile RawProfile => totals.TotalProfile;130131 public bool TryAddMaterial(ProcessedMaterial material)132 {133 if (Phase != BrewingPhase.NoIngredient)134 return false;135136 return totals.TryAdd(material);137 }138}139```140141## Pure Logic First142143Put deterministic rules in plain C# classes or structs:144145- Validators: `ValidateAddMaterial`, `ValidateStartBrew`, `ValidatePlacement`.146- Calculators: price, quality, score, XP, cooldown.147- Matchers: customer request match, recipe match, target selection.148- State helpers: stabilizers, phase transition rules, runtime statistics.149- Registries: maps from stable IDs to authoring assets.150151Rules:152- Keep Unity side effects out of rule code unless the rule is intrinsically visual or physics-bound.153- Return structured results, not just booleans, when UI/debug needs failure reasons.154- Write focused NUnit tests for these classes before adding scene-level tests.155156## Services And Bootstrap157158Use one composition root to instantiate persistent services, register them, load persistent scenes,159then initialize services in deterministic order.160161Rules:162- A service may own runtime state and coordinate side effects, but should not contain every business163 rule for the domain.164- Keep `ServiceLocator` calls near composition roots, UI adapters, and service boundaries. Avoid165 `ServiceLocator.Get<T>()` inside plain logic, modifiers, or data objects.166- Prefer interfaces for provider contracts when consumers only need a small surface.167- Provide explicit initialization priorities only when order matters.168- Unregister or clear static service registries during teardown or test reset.169- Missing required services should fail fast. Optional polish dependencies can be nullable.170171Service shape:172173```csharp174public sealed class BrewingService : InitializableServiceBase<BrewingService>, IBrewingProvider175{176 private BrewingSession session;177178 public override Task Initialize()179 {180 session = new BrewingSession();181 EventBus.Subscribe<RequestStartBrewEvent>(OnStartRequested);182 return Task.CompletedTask;183 }184185 protected override void OnDestroy()186 {187 EventBus.Unsubscribe<RequestStartBrewEvent>(OnStartRequested);188 base.OnDestroy();189 }190}191```192193## Event System194195Use typed event structs for broad notifications such as phase changes, UI readiness, item usage,196achievement unlocks, score changes, combat transitions, save/reset progress, and service readiness.197198Rules:199- Subscribe in `OnEnable`/`Initialize`; unsubscribe in the paired lifecycle method.200- Use request events for user/system intent and result events for state changes.201- Keep event definitions in domain event files.202- Avoid duplicated event names in different scopes unless there is a namespace-level reason.203- Avoid chains where event A publishes B publishes C without one workflow owner.204- Event bus debugging should expose subscriber counts and recent publish history.205- Isolate subscriber exceptions if a failure in one listener should not block the rest.206207## UI System208209UI renders state, publishes intent, and delegates rules to services or pure logic.210211Rules:212- Use reusable UI base components only for repeated mechanics: show/hide, modal pause, tabs,213 carousel, buttons, drag zones, effect displays.214- Split large screens into presenters/controllers for pagination, action buttons, effect previews,215 drop zones, animation, and service adapters.216- UI may cache services on enter/awake, but it should prefer provider interfaces when possible.217- If UI registers as a visual provider, it must unregister on close/exit/disable.218- Use a reference-counted pause manager for modal UI.219- Avoid `GameObject.Find`, tag lookup, and `Camera.main` in frequently used UI paths.220221## Save And Reset222223Centralize persistence behind generic save payloads and explicit reset orchestration.224225Rules:226- Every save payload derives from a base save type with explicit filename and reset policy.227- Async save/load returns `Task`. Reserve `async void` for Unity event entrypoints only.228- Do not fire-and-forget important saves during reset, scene changes, or quit flows.229- Separate platform IO, serialization, encryption/obfuscation, registry, and reset selection if the230 save manager grows large.231- Reset should delete matching save payloads, reset in-memory services by priority, and publish232 progress/completion events.233- Treat hardcoded keys and fixed IVs as obfuscation only; do not describe them as strong security.234235## Editor Tooling236237Build small editor tools for repetitive production tasks:238239- Event bus debugger.240- Service/bootstrap debugger.241- Bootstrap inspector with testing overrides.242- Selective save reset tools.243- Asset generators and validators for catalogs, recipes, cutscenes, scenes, audio, or content IDs.244245Rules:246- Put editor-only code under `Editor/` or wrap it in `#if UNITY_EDITOR`.247- Validate selected assets before generating output.248- Make generated folders deterministic and safe to overwrite only after confirmation.249250## Anti-Patterns To Fix251252### God MonoBehaviours Or Services253254Smell:255- One class handles input, pagination, state restore, service lookups, animation, audio, VFX,256 validation, saving, debug, and business rules.257258Fix:259- Extract validators, presenters, factories, runtime state objects, and side-effect services.260- Keep MonoBehaviours as Unity adapters/orchestrators.261262### Hidden Global Dependencies263264Smell:265- Frequent `ServiceLocator.Get<T>()`, `.Instance`, `FindObjectOfType`, `FindAnyObjectByType`,266 `GameObject.Find`, `FindGameObjectWithTag`, or `Camera.main` inside gameplay logic.267268Fix:269- Wire dependencies at bootstrap, through serialized fields, or constructors.270- Use interfaces for plain C# services and pass them through constructors.271- Cache optional lookups once at initialization.272273### Static Lifecycle Leaks274275Smell:276- Static service/event registries have no unregister or test reset path.277- Services keep references to destroyed scene UI or visual providers.278279Fix:280- Add explicit `Unregister`, `ClearAll`, or test teardown paths.281- Pair every register/subscribe with unregister/unsubscribe.282- Prefer weak/event ownership only when the lifecycle is genuinely shared.283284### Event Spaghetti285286Smell:287- Events are used as internal method calls, commands have no owner, or behavior requires tracing many288 publish/subscribe hops.289290Fix:291- Use one orchestrator per workflow.292- Use events for notifications and UI updates.293- Keep request/result event pairs explicit.294295### `Resources.Load` Drift296297Smell:298- Config and content dependencies are loaded through scattered string paths.299300Fix:301- Prefer serialized config references in bootstrap assets or service prefabs.302- If `Resources.LoadAll` is used for catalogs, keep paths centralized in one registry and validate303 loaded assets.304305### Async Fire-And-Forget306307Smell:308- Important saves, resets, or scene transitions are hidden behind `async void`.309310Fix:311- Return `Task` from service APIs and await at workflow boundaries.312- Keep `async void` only at Unity event entrypoints, with local exception handling.313314### Soft Failure For Required Wiring315316Smell:317- Required dependencies log a warning and continue with permissive behavior.318319Fix:320- Validate required references in `Awake`/`OnValidate`.321- Disable the component or throw a clear startup error when required wiring is absent.322323### Duplicate Or Ambiguous Types324325Smell:326- Two event structs/classes share the same name in different scopes without clear namespacing.327328Fix:329- Use domain-prefixed names such as `SettingsOpenRequestedEvent` or place all related events in one330 namespace/file.331332### Half-Built Abstractions333334Smell:335- Interfaces or enum branches exist but implementations are empty or no-op.336337Fix:338- Delete unused abstraction until needed, or complete behavior with focused tests/demo scene.339340## Review Checklist341342- [ ] Domain modules separate data, events, interfaces, logic, save data, assets, and services.343- [ ] Authoring data is in `ScriptableObject`; runtime state is not.344- [ ] Plain logic covers calculations, validation, matching, and phase transitions.345- [ ] Required dependencies are visible and validated.346- [ ] Services initialize from one composition root in deterministic order.347- [ ] ServiceLocator usage is confined to boundaries and supports cleanup.348- [ ] Event subscriptions are paired and event definitions are discoverable.349- [ ] UI renders state and publishes intent; gameplay rules live outside UI.350- [ ] Visual providers and listeners unregister on lifecycle exit.351- [ ] Factories create runtime instances and do not mutate shared assets.352- [ ] Large MonoBehaviours/services are split by responsibility.353- [ ] Save/load has awaitable lifecycle paths and clear reset categories.354- [ ] `Resources.Load` strings are centralized or replaced by serialized references.355- [ ] Debug logs are gated or removed from hot runtime paths.356- [ ] Editor tooling exists for repetitive data/setup work.357358## Output Style359360When asked to review a Unity codebase, lead with findings ordered by risk. Include file references,361why each pattern matters, and the smallest repair path. When asked to implement a design system,362make the standard real in one representative domain first, then leave a repeatable template for the363next domains.