TExcelTAD
Home › Unity with C# › State Machines

State Machines

An enemy that patrols, notices the player, chases, attacks and gives up is a pile of if statements waiting to happen: if (!isChasing && !isAttacking && canSeePlayer && !isStunned) …. A finite state machine (FSM) replaces the flags with one current state, each state owning its own behaviour and its own rules for leaving. You met the idea in the fundamentals course; this lesson builds the version Unity projects actually use.

Three common shapes

  1. enum + switch in one MonoBehaviour. Fine for 3–4 states.
  2. State classes (IState with Enter/Tick/Exit) owned by a plain C# machine. Scales to many states, testable without Unity.
  3. Visual tools: the Animator Controller (animation states), Unity's Behavior package (behaviour graphs), or Asset Store FSM/behaviour tree tools.

The state-class machine, runnable

The model below is the pattern you'd use in Unity, with a simulated world: the player's distance and line of sight change over a scripted sequence of ticks. Tick returns the next state (or null to stay), and the machine calls Exit and Enter on every change.

csharp · try it yourself
using System;

var guard = new Guard();
var fsm = new StateMachine(guard.Patrol);

double[] distances = { 20, 15, 9, 6, 3, 1.5, 1.5, 4, 10, 18, 25, 25, 25, 25, 25 };
for (int tick = 0; tick < distances.Length; tick++)
{
    guard.PlayerDistance = distances[tick];
    guard.Clock = tick * 0.5;                                  // half a second per tick
    fsm.Tick();
    Console.WriteLine(
quot;t={guard.Clock,4:F1}s dist={distances[tick],4:F1} state={fsm.Current.Name}"); } interface IState { string Name { get; } void Enter(); IState? Tick(); // return the next state, or null to stay void Exit(); } class StateMachine { public IState Current { get; private set; } public StateMachine(IState start) { Current = start; Current.Enter(); } public void Tick() { IState? next = Current.Tick(); if (next == null || next == Current) return; Current.Exit(); Console.WriteLine(
quot; {Current.Name} -> {next.Name}"); Current = next; Current.Enter(); } } class Guard { public double PlayerDistance, Clock; public const double SightRange = 10, AttackRange = 2, GiveUpAfter = 2.0; public readonly IState Patrol, Chase, Attack, Search; public Guard() { Patrol = new PatrolState(this); Chase = new ChaseState(this); Attack = new AttackState(this); Search = new SearchState(this); } public bool CanSeePlayer => PlayerDistance <= SightRange; } class PatrolState : IState { readonly Guard g; public PatrolState(Guard g) => this.g = g; public string Name => "Patrol"; public void Enter() { } public IState? Tick() => g.CanSeePlayer ? g.Chase : null; public void Exit() { } } class ChaseState : IState { readonly Guard g; public ChaseState(Guard g) => this.g = g; public string Name => "Chase"; public void Enter() => Console.WriteLine(" (shouts \"Halt!\")"); public IState? Tick() => g.PlayerDistance <= Guard.AttackRange ? g.Attack : !g.CanSeePlayer ? g.Search : null; public void Exit() { } } class AttackState : IState { readonly Guard g; public AttackState(Guard g) => this.g = g; public string Name => "Attack"; public void Enter() => Console.WriteLine(" (swings)"); public IState? Tick() => g.PlayerDistance > Guard.AttackRange ? g.Chase : null; public void Exit() { } } class SearchState : IState { readonly Guard g; double since; public SearchState(Guard g) => this.g = g; public string Name => "Search"; public void Enter() => since = g.Clock; public IState? Tick() => g.CanSeePlayer ? g.Chase : g.Clock - since >= Guard.GiveUpAfter ? g.Patrol : null; public void Exit() { } }
t= 0.0s dist=20.0 state=Patrol
t= 0.5s dist=15.0 state=Patrol
        Patrol -> Chase
        (shouts "Halt!")
t= 1.0s dist= 9.0 state=Chase
t= 1.5s dist= 6.0 state=Chase
t= 2.0s dist= 3.0 state=Chase
        Chase -> Attack
        (swings)
t= 2.5s dist= 1.5 state=Attack
t= 3.0s dist= 1.5 state=Attack
        Attack -> Chase
        (shouts "Halt!")
t= 3.5s dist= 4.0 state=Chase
t= 4.0s dist=10.0 state=Chase
        Chase -> Search
t= 4.5s dist=18.0 state=Search
t= 5.0s dist=25.0 state=Search
t= 5.5s dist=25.0 state=Search
t= 6.0s dist=25.0 state=Search
        Search -> Patrol
t= 6.5s dist=25.0 state=Patrol
t= 7.0s dist=25.0 state=Patrol

Each state is small and only knows its own exits. Adding a Stunned state means one new class and one new transition, not a new flag checked in five places.

The same machine in Unity

The states stay plain C#. A thin MonoBehaviour owns the machine, feeds it the world and ticks it:

csharp
using UnityEngine;
using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class GuardBrain : MonoBehaviour
{
    [SerializeField] Transform player;
    [SerializeField] Transform[] waypoints;
    public NavMeshAgent Agent { get; private set; }
    public Transform Player => player;
    public Transform[] Waypoints => waypoints;

    StateMachine machine;
    public IState Patrol, Chase, Attack, Search;

    void Awake()
    {
        Agent = GetComponent<NavMeshAgent>();
        Patrol = new PatrolState(this);
        Chase = new ChaseState(this);
        Attack = new AttackState(this);
        Search = new SearchState(this);
        machine = new StateMachine(Patrol);
    }

    void Update() => machine.Tick();

    public bool CanSeePlayer(float range)
    {
        Vector3 toPlayer = player.position - transform.position;
        if (toPlayer.sqrMagnitude > range * range) return false;
        // Line of sight: nothing on the Walls layer between us.
        return !Physics.Linecast(transform.position + Vector3.up, player.position + Vector3.up, LayerMask.GetMask("Walls"));
    }
}

public class ChaseState : IState
{
    readonly GuardBrain g;
    public ChaseState(GuardBrain g) => this.g = g;
    public string Name => "Chase";
    public void Enter() => g.Agent.speed = 5f;
    public IState Tick()
    {
        g.Agent.SetDestination(g.Player.position);
        if (Vector3.Distance(g.transform.position, g.Player.position) < 2f) return g.Attack;
        return g.CanSeePlayer(12f) ? null : g.Search;
    }
    public void Exit() { }
}

Tips

  • Show the current state in the Inspector or as a world-space label while developing. A debug label saves hours.
  • Use hysteresis: notice the player at 10 m but lose them at 12 m, so the guard doesn't flicker between states at exactly 10 m.
  • Hierarchical state machines (a Combat super-state containing Chase and Attack) and behaviour trees are the next steps when one flat FSM gets too big. See the Game AI course.

Test yourself

In the state-class pattern, which methods run when the machine changes from Chase to Attack?

  1. Attack.Exit then Chase.Enter
  2. Chase.Exit then Attack.Enter
  3. Only Attack.Tick
  4. Chase.Enter then Attack.Exit

A guard flickers between Chase and Search when the player stands exactly at sight range. What fixes it?

  1. A faster Update
  2. Hysteresis: a larger range for losing the player than for noticing them
  3. Removing the Search state
  4. Using FixedUpdate

Why keep state classes as plain C# instead of MonoBehaviours?

  1. MonoBehaviours can't have methods
  2. They can be created freely and tested without Unity, while one MonoBehaviour connects them to the scene
  3. Unity forbids interfaces on MonoBehaviours
  4. Plain classes run on the GPU