←All patterns
Behavioral

State

Give each mode of an object its own class so behaviour changes cleanly when the mode changes.

What Is It?

The State pattern moves mode-specific behaviour out of one giant switch and into separate classes. A character controller does not ask “am I jumping?” in twenty places; it simply forwards Tick() to whatever current state object it holds.

Each state implements a small interface — typically Enter(), Tick() and Exit() — and decides for itself which inputs it responds to and which state comes next. JumpState knows that landing is impossible mid-ascent; IdleState knows that pressing jump is fine.

A state machine owns the current state and performs transitions: it calls Exit() on the old state, swaps the reference, and calls Enter() on the new one. That is where animations get triggered, sounds play, and timers reset — once, at the right moment.

When Is It Used?

Use it for anything with distinct modes that respond differently to the same input: player movement (idle, run, jump, fall), enemy AI (patrol, chase, attack), doors, menus and game flow.

It pays off once you notice boolean flags multiplying (isJumping, isFalling, isAttacking) and conditions that check combinations of them. Each combination is really a state.

For two or three trivial modes, an enum with a switch is perfectly fine. Reach for state classes when behaviour per mode becomes large or transitions need setup and teardown.

Interactive Demo

Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.

State Pattern
stateIdletransitions0ignored0
MoveStopJumpJumpvy ≤ 0LandLand + held
Idle
Run
Jump
Fall
PlayerController
IdleState
moveInput: 0
Console
Press a button to see what happens…

Code

Assets / Scripts / Behavioral/ State ›PlayerController.cs
using UnityEngine;

namespace Patterns.Behavioral.State
{
    /// <summary>
    /// Context: owns the state machine and the shared data states need.
    /// Its Update is just "read input, tick the current state".
    /// </summary>
    [RequireComponent(typeof(Rigidbody2D))]
    public class PlayerController : MonoBehaviour
    {
        [SerializeField] private float runSpeed = 6f;
        [SerializeField] private float jumpSpeed = 12f;
        [SerializeField] private LayerMask groundMask;
        [SerializeField] private Transform feet;

        public Rigidbody2D Body { get; private set; }
        public Animator Animator { get; private set; }
        public StateMachine Machine { get; } = new();

        public IState Idle { get; private set; }
        public IState Run { get; private set; }
        public IState Jump { get; private set; }
        public IState Fall { get; private set; }

        public float MoveInput { get; private set; }
        public bool JumpPressed { get; private set; }
        public float JumpSpeed => jumpSpeed;
        public bool IsGrounded => Physics2D.OverlapCircle(feet.position, 0.1f, groundMask);

        private void Awake()
        {
            Body = GetComponent<Rigidbody2D>();
            Animator = GetComponentInChildren<Animator>();

            // Create each state once and reuse it.
            Idle = new IdleState(this);
            Run = new RunState(this);
            Jump = new JumpState(this);
            Fall = new FallState(this);
        }

        private void Start() => Machine.ChangeState(Idle);

        private void Update()
        {
            MoveInput = Input.GetAxisRaw("Horizontal");
            JumpPressed = Input.GetButtonDown("Jump") && IsGrounded;
            Machine.Tick();
        }

        public void Move(float direction) => Body.linearVelocityX = direction * runSpeed;
    }
}
4 files · namespace Patterns.Behavioral.StateC# · UTF-8 · LF

Before & After

Real-world smell: a player controller built on an enum and a switch. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

PlayerController keeps a Mode enum and runs one big switch (mode) in Update. Each case moves the player and decides the next mode, and SetMode plays the animation.

The jump impulse is duplicated in two cases, and every new mode (wall slide, dash, hurt) adds a case and touches the transitions of the others. Enter and exit logic has nowhere to live, so it ends up as more flags and checks scattered through the switch.

✓ What changed

  • The Mode enum, the switch and SetMode are gone. Idle, Run, Jump and Fall are IState objects created once in Awake.
  • Update now only reads input into MoveInput and JumpPressed and calls Machine.Tick().
  • The jump impulse is written once, in JumpState.Enter, and the animation cross-fade happens in the shared PlayerState.Enter.
  • What the states need (Body, IsGrounded, Move) is now public on the controller, so a new state is a new class that does not touch the existing ones.
PlayerController.Before.cs → PlayerController.After.cs+27/−42
11 using UnityEngine;
22
33 namespace Patterns.Behavioral.State
44 {
55 /// <summary>
6− /// Without State: one enum and one big switch decide everything.
7− /// Every mode's behaviour and every transition live in Update.
6+ /// With State: each mode is its own class with Enter/Tick/Exit.
7+ /// Update just reads input and ticks the current state.
88 /// </summary>
99 [RequireComponent(typeof(Rigidbody2D))]
1010 public class PlayerController : MonoBehaviour
1111 {
12− private enum Mode { Idle, Run, Jump, Fall }
13−
1412 [SerializeField] private float runSpeed = 6f;
1513 [SerializeField] private float jumpSpeed = 12f;
1614 [SerializeField] private LayerMask groundMask;
1715 [SerializeField] private Transform feet;
1816
19− private Rigidbody2D body;
20− private Animator animator;
21− private Mode mode = Mode.Idle;
17+ public Rigidbody2D Body { get; private set; }
18+ public Animator Animator { get; private set; }
19+ public StateMachine Machine { get; } = new();
2220
23− private bool IsGrounded => Physics2D.OverlapCircle(feet.position, 0.1f, groundMask);
21+ public IState Idle { get; private set; }
22+ public IState Run { get; private set; }
23+ public IState Jump { get; private set; }
24+ public IState Fall { get; private set; }
2425
26+ public float MoveInput { get; private set; }
27+ public bool JumpPressed { get; private set; }
28+ public float JumpSpeed => jumpSpeed;
29+ public bool IsGrounded => Physics2D.OverlapCircle(feet.position, 0.1f, groundMask);
30+
2531 private void Awake()
2632 {
27− body = GetComponent<Rigidbody2D>();
28− animator = GetComponentInChildren<Animator>();
33+ Body = GetComponent<Rigidbody2D>();
34+ Animator = GetComponentInChildren<Animator>();
35+
36+ Idle = new IdleState(this);
37+ Run = new RunState(this);
38+ Jump = new JumpState(this);
39+ Fall = new FallState(this);
2940 }
3041
42+ private void Start() => Machine.ChangeState(Idle);
43+
3144 private void Update()
3245 {
33− float input = Input.GetAxisRaw("Horizontal");
34− bool jump = Input.GetButtonDown("Jump") && IsGrounded;
35−
36− switch (mode)
37− {
38− case Mode.Idle:
39− if (jump) { body.linearVelocityY = jumpSpeed; SetMode(Mode.Jump); }
40− else if (input != 0f) SetMode(Mode.Run);
41− break;
42−
43− case Mode.Run:
44− body.linearVelocityX = input * runSpeed;
45− if (jump) { body.linearVelocityY = jumpSpeed; SetMode(Mode.Jump); }
46− else if (input == 0f) SetMode(Mode.Idle);
47− else if (!IsGrounded) SetMode(Mode.Fall);
48− break;
49−
50− case Mode.Jump:
51− body.linearVelocityX = input * runSpeed;
52− if (body.linearVelocityY <= 0f) SetMode(Mode.Fall);
53− break;
54−
55− case Mode.Fall:
56− body.linearVelocityX = input * runSpeed;
57− if (IsGrounded) SetMode(input == 0f ? Mode.Idle : Mode.Run);
58− break;
59− }
46+ MoveInput = Input.GetAxisRaw("Horizontal");
47+ JumpPressed = Input.GetButtonDown("Jump") && IsGrounded;
48+ Machine.Tick();
6049 }
6150
62− private void SetMode(Mode next)
63− {
64− mode = next;
65− animator.CrossFade(next.ToString(), 0.1f);
66− }
51+ public void Move(float direction) => Body.linearVelocityX = direction * runSpeed;
6752 }
6853 }

Advantages & Disadvantages

+ Advantages

  • Each mode lives in one class with its own logic, so it is easy to read, change and test.
  • Invalid transitions are impossible by construction — a state simply ignores input it does not handle.
  • Enter / Exit hooks give a single, reliable place for animation triggers and cleanup.

− Disadvantages

  • More classes and more indirection than a simple switch.
  • States often need access to the owner’s components, which can lead to wide context objects.
  • Flat state machines struggle with shared behaviour; you may need hierarchical states to avoid duplication.

Tips

  1. 01Pass a context (the controller) into each state’s constructor so it can read input and move the character without GetComponent calls.
  2. 02Create state instances once and reuse them; allocating a new state on every transition generates garbage.
  3. 03Keep transition logic inside states, and keep the machine dumb — it just swaps and calls Exit/Enter.
  4. 04Unity’s Animator is itself a state machine. Let your code FSM drive gameplay and set Animator parameters from Enter(), rather than reading gameplay state back out of the Animator.
  5. 05Log transitions during development (Idle → Run); it makes bugs in state flow obvious.