uw-state-machine
Skill44 starsChanged 8 months agoMITView on GitHub
Interface-based state machine patterns for Unity game states, character controllers, and UI flows. Use when implementing game flow (menu -> gameplay -> game over), character states (idle -> run -> jump -> fall), AI behavior states, or UI screen transitions. Triggers on "state machine", "game states", "character states", "screen flow", "game flow", "add states to", "idle/run/jump", "menu flow", "AI states", "boss phases", or any task involving managing discrete states with transitions between them. Reads ProjectConfig.yaml -> architecture_pattern to adapt patterns for SO-first or DI-first.
In this repository13 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- uw-code-reviewSkill
- uw-dependency-injectionSkill
- uw-game-feel-integratorSkill
- uw-network-setupSkill
- uw-scriptable-object-archSkill
- uw-skill-creatorSkill
- uw-ui-toolkit-binderSkill
- uw-unity-debuggingSkill
- uw-unity-editor-toolsSkill
- uw-unity-feature-scaffoldSkill
- uw-unity-project-setupSkill
- uw-unity-test-runnerSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
16 rules. About 0 are common, 2 are distinctive, and 14 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
14
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 15
Read docs/CODING_STANDARDS.md for async patterns (Awaitable + CancellationToken) — state transitions are async.
- Very specific: line 16
Ensure the feature has an .asmdef — create with uw-unity-feature-scaffold if needed.
- Distinctive: line 39
Only one state is active at a time.
- Very specific: line 59
If the current state implements IUpdatableState, the owner (a MonoBehaviour or update service) should call Update() each frame:
- Distinctive: line 206
Use for screen stacks where each screen manages its own visual state.
- Very specific: line 233
When architecture_pattern: "di-first", register the StateMachine and use a factory to create states with injected dependencies:
- Very specific: line 261
When architecture_pattern: "so-first", states can be MonoBehaviours with serialized transition references, or plain classes created in a …
- Very specific: line 284
Use uw-scriptable-object-arch event channels for communication between states and other systems.
- Very specific: line 288
Write tests: Use uw-unity-test-runner — test state transitions in EditMode by asserting CurrentState type after TransitionTo.
- Very specific: line 289
Add game feel: Use uw-game-feel-integrator for transition animations, screen effects between states.
- Very specific: line 290
Debug state issues: Use uw-unity-debugging if states aren't entering/exiting as expected.
- Very specific: line 295
Always pass CancellationToken to Enter and Exit — all async work inside states must respect cancellation.
- Very specific: line 299
Only one transition per frame — check conditions with early return after starting a transition.
- Very specific: line 300
All state machine code must live inside an .asmdef.
- Very specific: line 301
Use [SerializeField] private for any Inspector-exposed fields on MonoBehaviour owners.
- Very specific: line 302
If ProjectConfig.yaml -> mcp.unity_mcp is true, call refresh_unity after creating files.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
State Machine
Interface-based state machines for game flow, characters, and UI.
Before You Start
- Read
docs/ProjectConfig.yamlfor:architecture_pattern—"so-first"or"di-first"(affects how states and the StateMachine are created and wired).mcp.unity_mcp— iftrue, callrefresh_unityafter creating files.
- Read
docs/CODING_STANDARDS.mdfor async patterns (Awaitable+CancellationToken) — state transitions are async. - Ensure the feature has an
.asmdef— create withuw-unity-feature-scaffoldif needed.
Core Interface
public interface IState
{
Awaitable Enter(CancellationToken ct);
Awaitable Exit(CancellationToken ct);
}For states that need per-frame updates (character movement, AI ticking), extend with:
public interface IUpdatableState : IState
{
void Update();
}State Machine Service
Only one state is active at a time. Transitions are async to support loading screens, animations, and cleanup between states.
public class StateMachine
{
private IState _currentState;
public IState CurrentState => _currentState;
public async Awaitable TransitionTo(IState newState, CancellationToken ct)
{
if (_currentState != null)
await _currentState.Exit(ct);
_currentState = newState;
await _currentState.Enter(ct);
}
}If the current state implements IUpdatableState, the owner (a MonoBehaviour or update service) should call Update() each frame:
private void Update()
{
if (_stateMachine.CurrentState is IUpdatableState updatable)
updatable.Update();
}CancellationToken Lifecycle
States receive a CancellationToken in Enter and Exit. This token controls the lifetime of async work within that state — when the token cancels, any in-flight awaits should stop cleanly.
Where tokens come from:
// Per-scene token — cancels when the scene unloads
private CancellationTokenSource _sceneCts;
private void OnEnable()
{
_sceneCts = CancellationTokenSource.CreateLinkedTokenSource(
Application.exitCancellationToken);
}
private void OnDisable()
{
_sceneCts?.Cancel();
_sceneCts?.Dispose();
}Pass the token through transitions:
await _stateMachine.TransitionTo(new GamePlayState(_services), _sceneCts.Token);Inside a state, use the token for all async work:
public class LoadingState : IState
{
public async Awaitable Enter(CancellationToken ct)
{
await SceneManager.LoadSceneAsync("Level1", LoadSceneMode.Additive)
.WithCancellation(ct);
await LoadAssetsAsync(ct);
}
public async Awaitable Exit(CancellationToken ct)
{
// Cleanup — this also receives ct in case exit itself is async
}
}Common Implementations
Game Flow States
LoadingState -> LobbyState -> GamePlayState -> GameOverState
^ |
+------------------------------+Each state manages its own scene loading, UI, and services:
public class GamePlayState : IState
{
private readonly IScoreService _score;
private readonly IAudioService _audio;
public GamePlayState(IScoreService score, IAudioService audio)
{
_score = score;
_audio = audio;
}
public async Awaitable Enter(CancellationToken ct)
{
await SceneManager.LoadSceneAsync("GamePlay", LoadSceneMode.Additive)
.WithCancellation(ct);
_score.Reset();
_audio.PlayMusic(MusicTrack.Gameplay);
}
public async Awaitable Exit(CancellationToken ct)
{
_audio.StopMusic();
await SceneManager.UnloadSceneAsync("GamePlay")
.WithCancellation(ct);
}
}Character States
IdleState <-> RunState -> JumpState -> FallState
^ ^ | |
+-----------+-----------+-----------+Character states typically need per-frame updates and transition conditions:
public class CharacterIdleState : IUpdatableState
{
private readonly CharacterController _controller;
private readonly StateMachine _fsm;
private readonly CancellationToken _ct;
public CharacterIdleState(CharacterController controller, StateMachine fsm, CancellationToken ct)
{
_controller = controller;
_fsm = fsm;
_ct = ct;
}
public async Awaitable Enter(CancellationToken ct)
{
_controller.PlayAnimation("Idle");
}
public void Update()
{
if (_controller.MoveInput.magnitude > 0.1f)
{
_fsm.TransitionTo(
new CharacterRunState(_controller, _fsm, _ct), _ct).Forget();
}
}
public async Awaitable Exit(CancellationToken ct) { }
}UI Screen Flow
MainMenuScreen -> SettingsScreen -> ConfirmDialog
^ |
+-------------------------------+Use for screen stacks where each screen manages its own visual state. Each screen state shows/hides its UI root and handles input.
Conditional Transitions
For states with multiple exit paths, check conditions in Update() and transition to the appropriate next state:
public void Update()
{
if (_controller.IsGrounded && _controller.JumpPressed)
{
_fsm.TransitionTo(new JumpState(_controller, _fsm, _ct), _ct).Forget();
return; // Only one transition per frame
}
if (!_controller.IsGrounded)
{
_fsm.TransitionTo(new FallState(_controller, _fsm, _ct), _ct).Forget();
return;
}
}Only transition once per frame — check the most important condition first and return after starting a transition. Multiple transitions in the same frame cause race conditions.
DI Integration (di-first)
When architecture_pattern: "di-first", register the StateMachine and use a factory to create states with injected dependencies:
// In installer
public void InstallBindings(ContainerBuilder builder)
{
builder.AddSingleton(typeof(StateMachine));
builder.AddTransient(typeof(GamePlayState));
builder.AddTransient(typeof(GameOverState));
}States receive their dependencies via constructor injection — the container resolves them automatically:
public class GamePlayState : IState
{
[Inject] private readonly IScoreService _score;
[Inject] private readonly IAudioService _audio;
// Container creates this with all deps resolved
}See uw-dependency-injection for container setup, installer patterns, and the class taxonomy.
SO-First Integration (so-first)
When architecture_pattern: "so-first", states can be MonoBehaviours with serialized transition references, or plain classes created in a MonoBehaviour controller:
public class GameFlowController : MonoBehaviour
{
[SerializeField] private GameEvent _onGameStart;
[SerializeField] private GameEvent _onGameOver;
private StateMachine _fsm;
private void Awake()
{
_fsm = new StateMachine();
}
private async void Start()
{
var ct = destroyCancellationToken;
await _fsm.TransitionTo(new LobbyState(_onGameStart), ct);
}
}Use uw-scriptable-object-arch event channels for communication between states and other systems.
After Setup
- Write tests: Use
uw-unity-test-runner— test state transitions in EditMode by assertingCurrentStatetype afterTransitionTo. - Add game feel: Use
uw-game-feel-integratorfor transition animations, screen effects between states. - Debug state issues: Use
uw-unity-debuggingif states aren't entering/exiting as expected.
Rules
- One active state at a time per state machine.
- Always pass
CancellationTokentoEnterandExit— all async work inside states must respect cancellation. - Link CancellationTokens to
Application.exitCancellationTokenor scene lifetime. - States should not reference each other directly — transitions go through the StateMachine.
- Clean up subscriptions, event listeners, and spawned objects in
Exit(). - Only one transition per frame — check conditions with early
returnafter starting a transition. - All state machine code must live inside an
.asmdef. - Use
[SerializeField] privatefor any Inspector-exposed fields on MonoBehaviour owners. - If
ProjectConfig.yaml -> mcp.unity_mcpistrue, callrefresh_unityafter creating files.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

