Skip to content

State Machine

A State Machine is a commonly used pattern that allows you to isolate the complexity of multiple tasks in different nodes, in a way that each node is not aware of what others do.

About State Machines

For a full description of what a finite state machine is check this Wikipedia article.

Creating States

Let's start seeing how to create states before creating a state machine. A State is a single node unit from the state machine. To create one, create a class that inherits from the TState abstract class:

public class MyState1 : TState
{ }

A State has 3 virtual methods that can be overridden in order to execute its custom logic:

// Executed when the machine changes to this state
protected override void WhenEnter(IStateMachine stateMachine)
{ }

// Executed when the machine exits from this state
protected override void WhenExit(IStateMachine stateMachine)
{ }

// Executed every frame while this state is active
protected override void WhenUpdate(IStateMachine stateMachine)
{ }

A state has an IsActive property that can be queried to check if this state is currently the active one.

If you need to hook events to a State in order to make it work with other scripts, you can also subscribe to its event system.

// Executed when the machine changes to this state
event Action<IStateMachine, IState> EventOnEnter;

// Executed when the machine exits from this state
event Action<IStateMachine, IState> EventOnExit;

// Executed every frame while this state is active, right after the WhenUpdate(...)
event Action<IStateMachine, IState> EventOnBeforeUpdate;

For example, let's first create an instance of MyState1:

MyState1 state1 = new MyState1();

Now let's hook an external method that prints a message when the state is entered:

state1.EventOnEnter += this.OnEnterState;

The OnEnterState(...) method must have the following signature:

public void OnEnterState(IStateMachine machine, IState state)
{
    Debug.Log("Hello World!");
}

Creating a State Machine

To create a state machine, create a class that inherits from TStateMachine. The base class takes care of the logic of entering and exiting states, but it doesn't expose any public method. This allows you to decide which ones are available to other scripts:

public class MyStateMachine : TStateMachine
{ 
    public MyStateMachine(IState state) : base(state)
    { }

    public void Update()
    {
        this.OnUpdate();
    }

    public void ChangeState(IState state)
    {
        this.Change(state);
    }
}

First State

The constructor of the base class accepts the first state, which is the starting state that the machine will begin with. Entering this first state happens as soon as the machine is created.

The developer is responsible for calling its Update() method. We recommend calling it in a MonoBehaviour's Update().

To instruct the machine to change from one state to another, use the Change(IState) method (or the ChangeState(IState) public method from the previous example):

MyState1 state1 = new MyState1();
MyState2 state2 = new MyState2();

// Initialize with state1
MyStateMachine machine = new MyStateMachine(state1);

// Change to state2
machine.ChangeState(state2);

A State Machine also has 2 events that allow methods to be subscribed, which are launched as soon as there is a change in the currently active state:

event Action<IStateMachine, IState> EventStateEnter;
event Action<IStateMachine, IState> EventStateExit;

Putting it all together

The following example creates a state machine with two states that alternate every time the user presses the space key:

public class StateIdle : TState
{
    protected override void WhenEnter(IStateMachine stateMachine)
    {
        Debug.Log("Entered idle");
    }
}

public class StateAlert : TState
{
    protected override void WhenEnter(IStateMachine stateMachine)
    {
        Debug.Log("Entered alert");
    }

    protected override void WhenUpdate(IStateMachine stateMachine)
    {
        Debug.Log("Staying alert...");
    }
}

public class MyStateMachine : TStateMachine
{
    public MyStateMachine(IState state) : base(state)
    { }

    public void Update() => this.OnUpdate();
    public void ChangeState(IState state) => this.Change(state);
}

public class MyComponent : MonoBehaviour
{
    private StateIdle m_Idle;
    private StateAlert m_Alert;
    private MyStateMachine m_Machine;

    private void Awake()
    {
        this.m_Idle = new StateIdle();
        this.m_Alert = new StateAlert();
        this.m_Machine = new MyStateMachine(this.m_Idle);
    }

    private void Update()
    {
        if (Keyboard.current.spaceKey.wasPressedThisFrame)
        {
            this.m_Machine.ChangeState(this.m_Idle.IsActive ? this.m_Alert : this.m_Idle);
        }

        this.m_Machine.Update();
    }
}

Input System

This example uses the Keyboard class from Unity's Input System package (UnityEngine.InputSystem).