Uw State Machine logo

Uw State Machine

Community
devdavv
uw-state-machine

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.

Overview

Publisherdevdavv
Repositoryunity-ai-workflow
Skill nameuw-state-machine
Stars
46
Forks
6
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by devdavv on GitHub. Read the source before you install it.

Installation

Install the Uw State Machine AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/devdavv/unity-ai-workflow/tree/main/.claude/skills/uw-state-machine
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/devdavv/unity-ai-workflow.git /tmp/unity-ai-workflow
mkdir -p .claude/skills
cp -r /tmp/unity-ai-workflow/.claude/skills/uw-state-machine .claude/skills/uw-state-machine
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Uw State Machine in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Uw State Machine on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Uw State Machine is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

State Machine

Interface-based state machines for game flow, characters, and UI.

Before You Start

  1. Read docs/ProjectConfig.yaml for:
    • architecture_pattern — "so-first" or "di-first" (affects how states and the StateMachine are created and wired).
    • mcp.unity_mcp — if true, call refresh_unity after creating files.
  2. Read docs/CODING_STANDARDS.md for async patterns (Awaitable + CancellationToken) — state transitions are async.
  3. Ensure the feature has an .asmdef — create with uw-unity-feature-scaffold if needed.

Core Interface

csharp
public interface IState
{
    Awaitable Enter(CancellationToken ct);
    Awaitable Exit(CancellationToken ct);
}

For states that need per-frame updates (character movement, AI ticking), extend with:

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

csharp
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:

csharp
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:

csharp
// 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:

csharp
await _stateMachine.TransitionTo(new GamePlayState(_services), _sceneCts.Token);

Inside a state, use the token for all async work:

csharp
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:

csharp
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:

csharp
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:

csharp
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:

csharp
// 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:

csharp
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:

csharp
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 asserting CurrentState type after TransitionTo.
  • Add game feel: Use uw-game-feel-integrator for transition animations, screen effects between states.
  • Debug state issues: Use uw-unity-debugging if states aren't entering/exiting as expected.

Rules

  • One active state at a time per state machine.
  • Always pass CancellationToken to Enter and Exit — all async work inside states must respect cancellation.
  • Link CancellationTokens to Application.exitCancellationToken or 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 return after starting a transition.
  • All state machine code must live inside an .asmdef.
  • Use [SerializeField] private for any Inspector-exposed fields on MonoBehaviour owners.
  • If ProjectConfig.yaml -> mcp.unity_mcp is true, call refresh_unity after creating files.

Frequently asked questions

What does the Uw State Machine AI skill do?

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.

Why use Uw State Machine on TypingMind?

Because you install it once and use it with any model. Uw State Machine is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Uw State Machine in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/devdavv/unity-ai-workflow/tree/main/.claude/skills/uw-state-machine. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Uw State Machine?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Uw State Machine?

As many as you like. As long as a model supports skills, you can use Uw State Machine with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Uw State Machine AI skill free?

Yes. It is published on GitHub by devdavv under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇