iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🤖

A Memo on Implementing C# State Machine in Unity

に公開
2025/12/19

Introduction

I recently implemented a StateMachine in my game, so I'm writing this article as a memo for my future self. I've summarized everything from terminology to practice, aiming to make it as easy to understand as possible without unnecessary struggles. It's a bit long and includes some humor here and there, but I hope you'll feel free to read through it.

The Core Subject

First, a StateMachine is often defined as something that defines states in advance and acts according to those states. That makes sense in Japanese, but once you try to translate it into programming, it suddenly feels difficult.

Amidst this, a common, approachable form of a simple state machine is often cited as a combination of enum and switch.

The Limits of enum and switch

While switch isn't the main theme of this article, I'll include the code for comparison.

Example using enum and switch (click to expand)
public enum PlayerState
{
    Idle,
    Move,
    Jump,
    Dead
}

public class EnumPlayer : MonoBehaviour
{
    private PlayerState currentState = PlayerState.Idle;

    // Dummy inputs/state flags
    bool isDead;
    bool jumpPressed;
    bool moveInput;
    bool isGrounded;

    void Update()
    {
        switch (currentState)
        {
            case PlayerState.Idle:
                if (isDead)
                    currentState = PlayerState.Dead;
                else if (jumpPressed)
                    currentState = PlayerState.Jump;
                else if (moveInput)
                    currentState = PlayerState.Move;
                break;

            case PlayerState.Jump:
                if (isDead)
                    currentState = PlayerState.Dead;
                else if (isGrounded)
                    currentState = PlayerState.Idle;
                break;

            case PlayerState.Move:
                if (isDead)
                    currentState = PlayerState.Dead;
                else if (!moveInput)
                    currentState = PlayerState.Idle;
                break;

            case PlayerState.Dead:
                // Ideally, no transitions should happen here...
                // But since it's in the switch, it always forces you to "consider" it.
                break;
        }
    }
}

This has a weakness: since you have to write all transition logic inside the switch, it inevitably becomes bloated. Even if you try to handle it with if statements, the nesting becomes deep. (A state where there are many ifs.) You can see how difficult it becomes to read when nested in the example below.

Example of deep if-statement nesting
if (currentState == PlayerState.Idle)
{
    if (!isDead)
    {
        if (jumpPressed)
        {
            currentState = PlayerState.Jump;
        }
        else
        {
            if (moveInput)
            {
            // It's exhausting having to check if-statements 3 times just to reach here!
                currentState = PlayerState.Move;
            }
        }
    }
}

Returning to switch from if. For example, suppose you have three states defined in the enum: Idle, Jump, and Dead.

Obviously, the transition (Dead) → (Jump) shouldn't happen. It would be scary if you could jump while dead.

In this way, the switch code becomes bloated because it includes confirmations for transitions that are absolutely useless. The very first switch example is exactly such a bloated example.

Solution: Make States Classes

So, how can we solve this?

One solution is to write only the potential transition logic for each state within that state.

However, what you can define with enum is limited to names only; you cannot define logic or detailed information.

That's where the idea of the StateMachine comes in: defining the concept of a "state" as a class, which was previously defined just as a name in the enum.

It sounds suddenly difficult. The above concept might sound a bit complex, but the actual implementation is very simple.

A StateMachine is a "Concept," Not a "Correct Answer"

There is a reason it's simple. A StateMachine is a concept (a design pattern) of how to run a game, and the specific implementation method is not fixed.

Therefore, the implementation of a StateMachine differs from person to person.

So, depending on the scale of the game you are implementing, you are free to change the scale of that StateMachine.

If you feel resistance toward StateMachines, it's because the StateMachine code you first saw was too complex. Perhaps that was the moment you were instilled with resistance toward StateMachines.

This time, I will explain a [gentle] StateMachine that is as simple as possible and easy to extend to actual game production.

While the StateMachine in this article can handle medium-to-slightly-large games, it will break down at the large-scale commercial sales level, so I recommend referring to other articles for that.

Why does it break down? (It's too difficult and might break your brain, so it's better not to look)

I tried to make a joke in this tab, but the content was so advanced that I was barely able to explain it.
This might not be interesting, so I recommend skipping this!!


In this article, I am explaining a StateMachine with performance sufficient for most games.
However!
In large-scale commercial-level games, the simple StateMachine introduced this time will encounter the following types of problems.
Also, I'll list some fundamental structural issues, rather than superficial problems like "not being able to support FixedUpdate()."

1. The Problem of Not Being Able to Represent Hierarchical Structure

In actual games, a "parent-child relationship" is sometimes required for states.

Example: Fighting game character

Combat
├─ Ground
│  ├─ Idle
│  ├─ Walking
│  └─ Crouching
└─ Air
   ├─ Jumping Up
   ├─ Falling
   └─ Aerial Attack

Problem:
With this StateMachine, all states are flat.

  • There's no place to write "common processing when on the ground" (applying gravity, ground detection, etc.)
  • You have to repeatedly write "common processing when in the air" in each state (Up, Down, Attack)

Ideal Implementation:

// Parent state
public class GroundState : PlayerStateBase {
    public override void Update() {
        ApplyGroundPhysics(); // Ground common processing
        childState.Update(); // Call child state processing too
    }
}

// Child state
public class IdleState : GroundState {
    public override void Update() {
        base.Update(); // Call parent common processing
        // Idle specific processing
    }
}

With this implementation, hierarchical state management is not possible.

2. The Problem of Parallel States

In actual games, you need to manage multiple "independent states" at the same time.

Example: Action game character

  • Movement State: Idle / Walking / Running / Jumping
  • Attack State: No Attack / Weak Attack / Strong Attack
  • Damage State: Unharmed / Small Damage / Large Damage / Dead
  • Buff State: Normal / Speed UP / Attack UP

Problem:
This StateMachine can only have "one current state."

private IPlayerState currentState; // Only this one!

In other words, you cannot express a state of "attacking while running."
If you try to force it...

// Bad example: Combination explosion
public class RunAndWeakAttackState { }
public class RunAndStrongAttackState { }
public class WalkAndWeakAttackState { }
public class WalkAndStrongAttackState { }
public class JumpAndWeakAttackState { }
// ... Increasing infinitely!

Required number of states = Movement(4) × Attack(3) × Damage(4) × Buff(3) = 144!!

This is not realistic.

Ideal Implementation:

public class PlayerStateMachine {
    private IPlayerState movementState;  // Movement system
    private IPlayerState combatState;    // Combat system
    private IPlayerState damageState;    // Damage system
    private IPlayerState buffState;      // Buff system
    
    void Update() {
        movementState?.Update();
        combatState?.Update();
        damageState?.Update();
        buffState?.Update();
    }
}

With this implementation, you cannot manage multiple states in parallel.

3. The Data Sharing Problem Between States

In large-scale games, complex data needs to be passed between states.

Example: Combo System

public class AttackState1 : PlayerStateBase {
    void Update() {
        if (attackFinished) {
            // I want to pass "combo count" and "damage multiplier" to the next attack!
            stateMachine.SwitchState<AttackState2>();
        }
    }
}

Problem:
With this implementation, there is no mechanism to pass data when switching states.

public void SwitchState<T>() {
    // No arguments to pass data!
}

If implemented forcibly:

// Bad example: Let StateMachine hold all data
public class PlayerStateMachine {
    public int comboCount;        // For combos
    public float damageMultiplier; // For damage
    public Vector3 lastPosition;   // For position memory
    public bool wasJumping;        // For jump judgment
    // ... Continues to increase
}

With this, you won't understand "why this variable is needed," and the management will fail.

Ideal Implementation:

// Can pass data when transitioning states
public void SwitchState<T>(object data = null) where T : IPlayerState {
    currentState?.Exit();
    currentState = GetOrCreateState<T>();
    currentState.Enter(data); // Pass data!
}

// Receiver side
public class AttackState2 : PlayerStateBase {
    public override void Enter(object data) {
        var comboData = data as ComboData;
        int comboCount = comboData.count;
        // Now I can use the combo count
    }
}

With this implementation, data passing between states is difficult.

4. The State History Management Problem

Depending on the game, a "return to previous state" function is required.

Example:

  • Pause menu → Return to original state when closed
  • Receive damage → Return to original action when recovered
  • Cutscene → Return to interrupted state when finished

Problem:
This implementation does not retain history.

public void SwitchState<T>() {
    currentState?.Exit();
    currentState = newState; // Previous state disappears!
}

Ideal Implementation:

public class PlayerStateMachine {
    private Stack<IPlayerState> stateHistory; // Manage history with stack
    
    public void PushState<T>() {
        stateHistory.Push(currentState); // Save current state
        SwitchState<T>();
    }
    
    public void PopState() {
        if (stateHistory.Count > 0) {
            SwitchState(stateHistory.Pop()); // Return to previous state
        }
    }
}

With this implementation, state history cannot be managed.

Summary: Why does it break down?

This StateMachine is simple and easy to understand, but at a commercial level, it cannot handle the following requirements without modification:

  1. Hierarchical structure (parent-child states)
  2. Parallel states (managing multiple states simultaneously)
  3. Data passing (information sharing between states)
  4. History management (returning to previous state)

Implementing all of these would more than triple the amount of code.
Also, even with the above, it might be completely insufficient in some cases.

Therefore:

  • This simple implementation is sufficient for small-to-medium-sized games
  • For large-scale games, you may want to consider using external libraries in addition to C# implementation.

Just writing this gave me a headache, so let's move on quickly! It's too difficult!!

Four Entities That Make Up a StateMachine

Looking at source code suddenly is not good for mental health.
So, I will explain the StateMachine from the perspective of Japanese.

First, a StateMachine can be compared to a "company." You can understand the roles by thinking of the components of a StateMachine as the following four people.

Role (Metaphor) Specific Class Name (Example) What they do
① Field Supervisor PlayerStateMachine Gives instructions like "Next is Idle duty, it's your turn!" or "Next is Move duty!"
② Worker PlayerIdleState, etc. Works by saying "Hey! I'll play the idle animation!" or "I'll process movement!"
③ Instruction Manual for Workers IPlayerState Something that allows the supervisor to understand at a glance what kind of work the worker will do when they see it
④ Company Smartphone PlayerStateBase Connects the supervisor's contact (variable) and workers (states) so they can pass requests between them

Relationships Between Them

  1. The Field Supervisor (StateMachine) always sends only one Worker (State) to the field.
  2. The Worker who went to the field works exclusively on their own job (idle or move).
  3. Thanks to the Instruction Manual (Interface), the supervisor can immediately understand what work will be done just by looking at the manual, regardless of which worker comes.
  4. Thanks to the Company Smartphone (Base Class), workers and supervisors can contact each other when they want to.

Moving the player with this "four-person team" is the StateMachine.

Why is the ③ Worker's Instruction Manual needed?

The ③ Worker's Instruction Manual exists so that the ① Field Supervisor can properly manage the ② Workers.
If the way the ② manual is written is different for every state, the ① Field Supervisor would be confused when reading the manuals.
The role of the worker's instruction manual is to fulfill the request, "Unify the writing style!"

Why is the ④ Company Smartphone needed?

It is used when a worker wants to say "I want to quit my current job and do another one!" (change state) or when they want to contact the Field Supervisor.
I will explain the details later, but having this allows workers to contact the Field Supervisor.

Let's Look at Actual Code

Now, let's look at the actual code. I will explain from the top (Worker's Instruction Manual → Company Smartphone → Field Supervisor → Worker).

③ Worker's Instruction Manual: IPlayerState (interface)

public interface IPlayerState
{
    // Process executed only once when entering a state
    void Enter();

    // Process executed every frame (Update)
    void Update();

    // Process executed only once when leaving a state
    void Exit();
}

Role of this code:

  • Enter() : Called only once the moment you enter the state (e.g., start animation)
  • Update() : Called every frame (e.g., input check, movement processing)
  • Exit() : Called only once the moment you leave the state (e.g., end animation)

"Forcing these three methods on all workers" is the role of the interface (instruction manual).

What is an interface?

interface = A contract that must be kept

It is a rule that "a class implementing this must absolutely have these methods!"

// interface definition
// Interface naming convention starts with a capital I
public interface ISHatiku
{
    void Work();  // Must have a "Work" method!
}

// Class implementing the interface
public class Majime : ISHatiku
{
    public void Work()  // Error if not implemented!
    {
        Debug.Log("I'll work overtime!");
    }
}

public class Sabori : ISHatiku
{
    public void Work()
    {
        Debug.Log("I'll go home at closing time!");
    }
}

Usage example and result:

IShachikumind employee = new Majime();
employee.Work();  // Output: I'll work overtime!

employee = new Sabori();
employee.Work();  // Output: I'll go home at closing time!

Point: Whether Majime or Sabori, since it is guaranteed that Work() exists, you can call it with peace of mind.

In this case, a class implementing IPlayerState must have the three methods Enter(), Update(), and Exit().

From the Field Supervisor's perspective, they can be relieved, thinking "No matter which worker comes, if I call Enter(), they'll start working, and if I call Exit(), their work will end."

④ Company Smartphone: PlayerStateBase (Parent class)

Here, I'll insert a convenient parent class.
You might see many unfamiliar words, but I've included detailed explanations of the words at the end of the code.

public abstract class PlayerStateBase : IPlayerState
{
    // This is the "Company Smartphone" that appeared in the example.
    // It allows all workers (States) to have contact information for the Field Supervisor (StateMachine) from the beginning.
    protected PlayerStateMachine stateMachine;

    // This is the constructor (initialization method) that sets the contact information
    public PlayerStateBase(PlayerStateMachine stateMachine)
    {
        this.stateMachine = stateMachine;
    }

    // abstract methods are methods that must be implemented in the inherited class
    public abstract void Enter();
    public abstract void Update();
    public abstract void Exit();
}
What is inheritance?

inheritance = Inheriting the functions of a parent class

It's a mechanism where you can "add or change while using existing functions as they are."
Represented by : ClassName.

// Parent class
public class Human
{
    public void Study() => Debug.Log("Grades up!");
}

// Child class (inherits with :)
public class Sabori : Human
{
    public void Saboru() => Debug.Log("Grades down!");
}

Usage example and result:

Human Sabori = new Sabori();
Sabori.Study();   // Output: Grades up! (Even a slacker is a human, so grades go up if they study)
Sabori.Saboru();  // Output: Grades down! (A slacker can slack off in addition to normal human functions!)
What is new?

new = Keyword to create an entity from a blueprint (class)

Since a class is a "blueprint," it cannot be used as is. You create an "entity" with new.

public class Sabori
{
    public string reason;
}

Usage example:

Sabori tanaka = new Sabori();  // Create entity from blueprint
tanaka.reason = "Overslept due to staying up late reading manga";

Sabori suzuki = new Sabori();   // Create another entity
suzuki.reason = "Fake sick to play games";
// Although it's the same slacking off, the content of Tanaka's and Suzuki's slacking is different!

I have never used new once in Unity tutorials!!

In Unity, components inheriting from MonoBehaviour are not directly new-ed by developers, but managed by Unity.

// It is wrong (forbidden) to write components like this in Unity
// Rigidbody rb = new Rigidbody(); 

// Instead, get a component that is already attached
Rigidbody rb = GetComponent<Rigidbody>();

// For normal classes (without MonoBehaviour inheritance), it's OK to new
List<int> numbers = new List<int>();

And in this StateMachine, the state class does not inherit MonoBehaviour, so you have to new it yourself!

Then, why not just inherit MonoBehaviour!
It might occur to you to think that, but if you inherit MonoBehaviour, it won't work unless you attach it to a GameObject. A state class is a concept/rule like "idle" or "moving," not an "object" to place in a scene. Creating a GameObject just to attach it is like building a post office every time you want to send a letter. That is not an optimal solution, right?

What is override?

override = Overwriting a parent's method

You can change an action defined in the parent class to be "your own style" in the child class.

public class Human
{
    public virtual void Study()  // Declare "overwritable" with virtual
    {
        Debug.Log("I'll studyーーーー");
    }
}

public class Sabori : Human  // Sabori inherits Human
{
    public override void Study()  // Overwrite with override
    {
        Debug.Log("Study?? I don't know about that. I'm gonna slack off!!");
    }
}

Usage example and result:

Sabori sabori = new Sabori();
sabori.Study();  // Output: Study?? I don't know about that. I'm gonna slack off!!

Oh my, Study() was overwritten and they slacked off...
It was "I'll studyーーーー" in the Human class, but the content changed when I did override in the Sabori class!

What is abstract?

abstract = Blueprint (cannot be used directly)

It means "this class is a blueprint, not something to be used directly."
The difference from virtual, which indicates that processing can be replaced in the inheritance destination, is that with abstract, the parent does not decide the content. It forces implementation in the child class.

// Abstract class (blueprint)
public abstract class Human
{
    public abstract void Saboru();  // Don't write the content! Write it in the inheritance destination!
}

// Inherit and implement concretely
public class SuperSabori : Human
{
    public override void Saboru()  // Write content for the first time here
    {
        Debug.Log("I will slack off with all my might!!!");
    }
}

Example that becomes an error:

Human human = new Human();        // Error! Cannot new abstract directly
Human human = new SuperSabori();  // OK! Can new an inherited class

Similarly, you cannot write new PlayerStateBase() directly for PlayerStateBase. PlayerIdleState and PlayerMoveState inherit this and use it.

What is protected?

protected = A secret only between parent and child (Is that romantic?)

Let's look at the differences in access modifiers with concrete examples:
(For convenience, variable names are in Japanese)

public class Parent 
{
    public string FamilyEntrance = "Visible to anyone";       // Also OK from external
    protected string FamilyRefrigerator = "Parent and child only by manners";     // OK from child class
    private string ParentSalaryStatement = "Parent's secret";     // NG even from child class
}

public class Children : Parent  // Create a child inheriting from the parent)
{
    void Test()
    {
        Debug.Log(FamilyEntrance);     // OK
        Debug.Log(FamilyRefrigerator);  // OK (Visible because parent and child)
        Debug.Log(ParentSalaryStatement);    // Error! (Parent's secret)
    }
}

public class TotalStranger 
{
    void Test()
    {
        Parent p = new Parent();
        Debug.Log(p.FamilyEntrance);     // OK
        Debug.Log(p.FamilyRefrigerator);  // Error! (Not parent and child)
        Debug.Log(p.ParentSalaryStatement);    // Error!
    }
}

This stateMachine variable is protected, so it can be accessed from child classes (PlayerIdleState, etc.).

Why make it protected?

  • To ask the commander "change to the next state!" from each state, you need to access the stateMachine
  • private is NG because it cannot be accessed from child classes (the states)
  • It works with public too, but then anyone can see it from the outside (revealing more than necessary)
  • protected limits it to "parent and child only," which is just right!

This is based on the design principle of "making the disclosure range the minimum necessary."
(Called encapsulation)

Why write Enter() twice for abstract and interface?

This is because the interface forces methods to be held.

First, PlayerStateBase needs to implement (keep the promise) the IPlayerState interface.
However, this parent class itself does not know the "concrete content (how it moves)."

Therefore, by declaring abstract (leave the content to the children!), it does a "responsibility pass":

  1. Formally keeps the interface promise (holding the method)
  2. But actually throws the actual content to the children (Idle, Move) that inherit this class

Why hold stateMachine?

protected PlayerStateMachine stateMachine;

This is super important.

Each worker (state) sometimes thinks, "I want to transition to another state (switch jobs) myself." For example:

Idle → If space key is pressed → I want to switch to Jump duty

At this time, the worker needs to ask the Field Supervisor (PlayerStateMachine), "Please change my duty!"

This stateMachine variable is the contact information for making that request.

If you look at the ① code below, you should see a method called SwitchState().
Since the Field Supervisor (stateMachine) holds the command called SwitchState() to "change duty," the state can ask to "please change to the next duty!" by calling that command.

① Field Supervisor: PlayerStateMachine

using UnityEngine;
using System.Collections.Generic;

public class PlayerStateMachine : MonoBehaviour
{
    // Currently active state
    private IPlayerState currentState;

    // Dictionary holding all states
    private Dictionary<System.Type, IPlayerState> states;

    // Here, you keep/reference data required by states, such as player components
    // public Rigidbody rb;
    // public Animator anim;

    void Awake()
    {
        // State instantiation
        // Since the state machine expresses states as classes, it is not a mere value like an enum,
        // but must be created as a concrete instance using the new keyword.
        states = new Dictionary<System.Type, IPlayerState>()
        {
            { typeof(PlayerIdleState), new PlayerIdleState(this) },
            { typeof(PlayerMoveState), new PlayerMoveState(this) },
            // Add other states here
        };

        // Set initial state
        SwitchState(typeof(PlayerIdleState));
    }

    void Update()
    {
        // Call Update method of the current state
        currentState?.Update();
    }

    // Since this is public, it can be called from state classes.
    // Making this called is a big reason for letting the constructor receive this class
    public void SwitchState(System.Type newStateType)
    {
        // If there is an existing state, call Exit
        if (currentState != null)
        {
            currentState.Exit();
        }

        // Get new state
        if (states.TryGetValue(newStateType, out IPlayerState newState))
        {
            currentState = newState;
            // Call Enter of new state
            currentState.Enter();
        }
        else
        {
            Debug.LogError($"State not found: {newStateType}");
        }
    }
}

Role of this code (Super important!!):

Part Role
currentState The worker currently on the field. Works every frame in Update()
states List of all workers hired. Searches using "PlayerIdleState" class name itself as a search key
Awake() Hires (new) all workers at game start and decides initial duty
Update() Calls the current worker's Update() every frame (Work!)
SwitchState() Switches state. Executed in order of Exit → currentState change → Enter

Point:

  • Since this class inherits MonoBehaviour, it can be attached to a GameObject
  • If you attach this to the player character, the state machine starts moving!
What is Dictionary?

Dictionary = A box that can store names and values as a set

It's in a list-like form, and in addition, you can give keywords to the variables inside.
In other words, you can identify them even if the order of the variables inside is scattered.
Dictionary is amazing!!

// Dictionary<Key type, Value type>
Dictionary<string, int> powerLevels = new Dictionary<string, int>()
{
    { "Hero", 9999 },
    { "DemonKing", 530000 },
    { "VillagerA", 5 }
};

Usage example and result:

// Way using normal variables
int heroPower = 9999;
Debug.Log(heroPower);  // Output: 9999

// Way using Dictionary of the example above
int villagerPower = powerLevels["VillagerA"];
Debug.Log(villagerPower);  // Output: 5 (Trash...)

What we are doing with Dictionary

Dictionary<System.Type, IPlayerState> states;

With this single line, we are doing the following two things at the same time.

  1. IPlayerState (filtering)
    Restricting so only classes (workers) inheriting IPlayerState can be registered. This prevents unrelated classes from mixing in.

  2. System.Type (safe key)
    By using "type" instead of a string as a key, an error will occur immediately if there is a spelling mistake.

By setting these two conditions when declaring the Dictionary, the code becomes stable.

A little application

This time, I am generating all states first for clarity, but there is also a design for lazy generation that generates at the timing it is needed.

Also, to simplify the explanation in this article, I am using the old Input (Input Manager).
Since the use of "Input System (New Input)" is recommended in current Unity,
I recommend using that for actual development.

Note that Input Manager will also continue to work properly as long as Unity does not discontinue it.

② Worker: Specific state class

Now, let's finally make specific states.
If you want to increase states, such as during double-jump or during a tutorial, imitate the code below.

PlayerIdleState (idle state)

using UnityEngine;

public class PlayerIdleState : PlayerStateBase
{
    public PlayerIdleState(PlayerStateMachine stateMachine) : base(stateMachine)
    {
        // Call parent class constructor with base(stateMachine) and set contact information to Field Supervisor
    }

    public override void Enter()
    {
        Debug.Log("Entered idle state");
        // Set animation to idle state here
        // stateMachine.animator.SetBool("isIdle", true);
    }

    public override void Update()
    {
        // Transition to move state when right arrow key is pressed
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            // Ask Field Supervisor "Please change to move duty!"
            stateMachine.SwitchState(typeof(PlayerMoveState));
        }
    }

    public override void Exit()
    {
        Debug.Log("Exiting idle state");
        // stateMachine.animator.SetBool("isIdle", false);
    }
}
What is : base(stateMachine)? Why is it needed?

Purpose: Each state wants to switch states by calling stateMachine.SwitchState()

Problem: Since the stateMachine variable is in the parent class, it will not be set unless the parent's initialization is called

**Execution flow (following in order):

When the Field Supervisor creates a state, it writes:

new PlayerIdleState(this)  // this is the Field Supervisor itself

↓ Step 1: Enter child class constructor

// PlayerIdleState.cs
public PlayerIdleState(PlayerStateMachine stateMachine) : base(stateMachine)
//                     Receive Field Supervisor here            ↓ Pass to parent immediately

↓ Step 2: Parent constructor is executed first due to : base(stateMachine)

// PlayerStateBase.cs (parent class)
public PlayerStateBase(PlayerStateMachine stateMachine)
{
    this.stateMachine = stateMachine;  // Set to variable here!
}

↓ Step 3: After parent initialization is complete, { } inside child is executed

// Back to PlayerIdleState.cs
public PlayerIdleState(PlayerStateMachine stateMachine) : base(stateMachine)
{
    // When this line is called, the parent already has the stateMachine,
    // and since this is inside a class that inherits it, stateMachine is in a usable state.
}

↓ Result: stateMachine.SwitchState() can be called from child class

What if I didn't write : base(stateMachine)?
→ Parent constructor is not executed, and stateMachine remains null
→ NullReferenceException (commonly known as: NullPointer) occurs the moment SwitchState() is called.

Summary in one word:
Essential spell to "register the contact information for the Field Supervisor to the parent class."

Why not write it directly in the child class?

You might think, "I should just have the child class hold the stateMachine variable and set it myself!" I thought so too. But I seem to have been ignorant.

Method Effort Merits/Demerits
Write everything in child class Write every time Write the same code 10 times if there are 10 states... annoying!
Write once in parent class Only once Child class only needs to write : base()! Easy!

"Because I didn't want to write the same code over and over, I grouped it in the parent."
(Called the DRY principle)

PlayerMoveState (move state)

using UnityEngine;

public class PlayerMoveState : PlayerStateBase
{
    public PlayerMoveState(PlayerStateMachine stateMachine) : base(stateMachine)
    {
    }

    public override void Enter()
    {
        Debug.Log("Entered move state");
        // stateMachine.animator.SetBool("isRunning", true);
    }

    public override void Update()
    {
        // Transition to idle state when right arrow key is released (not pressed)
        if (!Input.GetKey(KeyCode.RightArrow))
        {
            stateMachine.SwitchState(typeof(PlayerIdleState));
        }
        
        // Write actual movement processing here
        // float moveSpeed = 5f;
        // stateMachine.rb.velocity = new Vector3(1f * moveSpeed, ...); // Move right
    }

    public override void Exit()
    {
        Debug.Log("Exiting move state");
        // stateMachine.animator.SetBool("isRunning", false);
    }
}

Point: Transition logic is written per state

This is the part that overcomes the weaknesses of enum and switch.

  • PlayerIdleState only knows "transition to PlayerMoveState when move key is pressed"
  • PlayerMoveState only knows "transition to PlayerIdleState when move key is released"

There is no need to write code for transitions that will never happen.

For example, even if you added PlayerDeadState (dead state), there is no need to write code transitioning from there to the jump state.

StateMachine Flow (Chronological)

Let's follow the flow from game start to state transition in order.

1. Game start → Awake() is called

void Awake()
{
    // new all states here and register to Dictionary
    states = new Dictionary<System.Type, IPlayerState>()
    {
        { typeof(PlayerIdleState), new PlayerIdleState(this) },
        { typeof(PlayerMoveState), new PlayerMoveState(this) },
    };
    
    // Set initial state
    SwitchState(typeof(PlayerIdleState));
}

What happens at this point:

  • Instance of all states created
  • SwitchState() called, and PlayerIdleState becomes the current state
  • Enter() of PlayerIdleState executed → Displays "Entered idle state"

2. Every frame → Update() is called

void Update()
{
    currentState?.Update();  // Call Update of current state
}

What happens at this point:

  • Since it is currently PlayerIdleState, PlayerIdleState.Update() is executed every frame
  • Checking "was move key pressed?" within Update

3. User presses move key

// Inside PlayerIdleState.Update()
  if (Input.GetKeyDown(KeyCode.RightArrow))
{
    stateMachine.SwitchState(typeof(PlayerMoveState));
}

What happens at this point:

  • Detect move key input!
  • Ask the commander "change to PlayerMoveState!"

4. SwitchState() is executed

public void SwitchState(System.Type newStateType)
{
    currentState.Exit();           // Exit process of current state
    currentState = states[newStateType];  // Switch state
    currentState.Enter();          // Start process of new state
}

What happens at this point:

  • PlayerIdleState.Exit() → Displays "Exiting idle state"
  • currentState switches to PlayerMoveState
  • PlayerMoveState.Enter() → Displays "Entered move state"

5. From then on, Update of the new state is called every frame

void Update()
{
    currentState?.Update();  // This time PlayerMoveState.Update() is called
}

What happens at this point:

  • PlayerMoveState.Update() executed every frame
  • If move key is released, return to PlayerIdleState again with SwitchState()

The above is the basic 1-cycle flow of the StateMachine.
Enter → Update (repeated) → Exit → Enter of next state... This cycle continues.

Summary

Class Name (Example) Metaphor (Company) Summary
IPlayerState Instruction Manual "Must absolutely implement these 3 methods!"
PlayerStateBase Company Smartphone (parent class) "I'll hold the contact info for the Field Supervisor"
PlayerStateMachine Field Supervisor "I'll manage which state it is now, and rotate Update"
PlayerIdleState Worker (concrete class) "I'll define behavior, but I won't move myself!"

Finally

Did this reduce your resistance toward StateMachines even a little bit?

If written with enum and switch, you had to write all transition patterns in one place.
If it's a class-based StateMachine, I think the biggest benefit of a StateMachine is being able to write "only transitions related to oneself" for each state.

Depending on the person, there are StateMachines that would take a year just to read the code, but a basic StateMachine is code like the above.
A StateMachine itself is an abstract concept, so there is no single correct answer to the implementation method.
I think there are other StateMachines that are easy to understand and have high versatility.

Bonus: If you want to evolve it into a strongest machine

This StateMachine is the minimum configuration, but if you want to develop it, you can add functions like:

  • Addition of FixedUpdate() - If you want to perform physical calculations in FixedUpdate
  • Abstraction of state transition conditions - Make transition conditions classes too, making them more flexible

A big advantage of StateMachines is that they can be customized freely, but customization is tough without technical skills...

I am also learning StateMachines, so if I make a good one, I'll write another article.
Thank you for watching until the end!!
If there are mistakes or differences in understanding, I would appreciate it if you could tell me in the discussion column.

Discussion