←All patterns
Behavioral

Command

Wrap an action in an object so it can be queued, logged, replayed or undone.

What Is It?

The Command pattern turns a request into a standalone object. Instead of calling unit.Move(Vector2Int.up) directly, you create a MoveCommand that remembers who to act on and what to do, then hand it to an invoker that decides when to run it.

Every command implements the same tiny interface — usually Execute() and Undo(). Because the invoker only sees ICommand, it can push commands onto a history stack, pop them to undo, and push them onto a redo stack without knowing anything about movement, building or inventory.

Think of a tactics game on a grid: each tile step the player takes becomes a MoveCommand. Undo walks the unit back exactly one tile, redo replays it, and the same history can drive a replay system or a network log of player inputs.

When Is It Used?

Use it when actions must be reversible: level editors, puzzle games, turn-based tactics, and anything with an undo button.

It is also a natural fit for input remapping, macro recording, deterministic replays and sending player intent over the network, since a command is just data plus a method.

Skip it for continuous, per-frame actions such as analog movement in an action game. Wrapping every Update tick in an object adds garbage and complexity with little payoff.

Interactive Demo

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

Command Pattern
pos2,2undo0redo0
GridUnit · Receiver
♞
CommandInvoker
undoStack0
empty
redoStack0
empty
top of stack ↑
Console
Press a button to see what happens…

Code

Assets / Scripts / Behavioral/ Command ›InputHandler.cs
using UnityEngine;

namespace Patterns.Behavioral.Command
{
    /// <summary>
    /// Client: turns key presses into command objects and hands them
    /// to the invoker. It never moves the unit itself.
    /// </summary>
    public class InputHandler : MonoBehaviour
    {
        [SerializeField] private Transform unit;
        [SerializeField] private RectInt board = new(0, 0, 5, 5);

        private readonly CommandInvoker invoker = new();

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.W)) Move(Vector2Int.up);
            if (Input.GetKeyDown(KeyCode.S)) Move(Vector2Int.down);
            if (Input.GetKeyDown(KeyCode.A)) Move(Vector2Int.left);
            if (Input.GetKeyDown(KeyCode.D)) Move(Vector2Int.right);

            if (Input.GetKeyDown(KeyCode.Z)) invoker.Undo();
            if (Input.GetKeyDown(KeyCode.Y)) invoker.Redo();
        }

        private void Move(Vector2Int direction)
        {
            invoker.Execute(new MoveCommand(unit, direction, board));
        }
    }
}
4 files · namespace Patterns.Behavioral.CommandC# · UTF-8 · LF

Before & After

Real-world smell: an input handler that also owns the undo history. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

InputHandler reads the keys, checks the board bounds, moves the unit and keeps two Stack<Vector3> histories, all in one MonoBehaviour.

The history only knows positions, so the first action that is not a move (rotating, placing a tile, using an item) cannot be undone without a second pair of stacks. Moving the same unit from AI, a replay or the network means copying the bounds check and the history bookkeeping into that code too.

✓ What changed

  • The position stacks and the hand-written Undo/Redo methods are gone; CommandInvoker owns the history for every kind of action.
  • Move now just builds a MoveCommand and hands it to invoker.Execute. The bounds check and the previous position live inside the command.
  • A new action is a new ICommand class. Input, AI or a replay system can all push it through the same invoker, and undo works for it automatically.
InputHandler.Before.cs → InputHandler.After.cs+6/−31
1−using System.Collections.Generic;
21 using UnityEngine;
32
43 namespace Patterns.Behavioral.Command
54 {
65 /// <summary>
7− /// Without Command: reading input, moving the unit and keeping the
8− /// undo history are all tangled together in one MonoBehaviour.
6+ /// With Command: input only creates command objects. The invoker owns
7+ /// the history, and each command knows how to undo itself.
98 /// </summary>
109 public class InputHandler : MonoBehaviour
1110 {
1211 [SerializeField] private Transform unit;
1312 [SerializeField] private RectInt board = new(0, 0, 5, 5);
1413
15− // The history only stores positions, so moving is the only thing that can be undone.
16− private readonly Stack<Vector3> undoPositions = new();
17− private readonly Stack<Vector3> redoPositions = new();
14+ private readonly CommandInvoker invoker = new();
1815
1916 private void Update()
2017 {
2118 if (Input.GetKeyDown(KeyCode.W)) Move(Vector2Int.up);
2219 if (Input.GetKeyDown(KeyCode.S)) Move(Vector2Int.down);
2320 if (Input.GetKeyDown(KeyCode.A)) Move(Vector2Int.left);
2421 if (Input.GetKeyDown(KeyCode.D)) Move(Vector2Int.right);
2522
26− if (Input.GetKeyDown(KeyCode.Z)) Undo();
27− if (Input.GetKeyDown(KeyCode.Y)) Redo();
23+ if (Input.GetKeyDown(KeyCode.Z)) invoker.Undo();
24+ if (Input.GetKeyDown(KeyCode.Y)) invoker.Redo();
2825 }
2926
3027 private void Move(Vector2Int direction)
3128 {
32− Vector3 target = unit.position + new Vector3(direction.x, direction.y, 0f);
33− if (!board.Contains(Vector2Int.RoundToInt(target)))
34− return;
35−
36− undoPositions.Push(unit.position);
37− redoPositions.Clear();
38− unit.position = target;
29+ invoker.Execute(new MoveCommand(unit, direction, board));
3930 }
40−
41− private void Undo()
42− {
43− if (undoPositions.Count == 0) return;
44−
45− redoPositions.Push(unit.position);
46− unit.position = undoPositions.Pop();
47− }
48−
49− private void Redo()
50− {
51− if (redoPositions.Count == 0) return;
52−
53− undoPositions.Push(unit.position);
54− unit.position = redoPositions.Pop();
55− }
5631 }
5732 }

Advantages & Disadvantages

+ Advantages

  • Undo and redo become a matter of two stacks instead of special-case code everywhere.
  • Decouples the code that triggers an action (input, AI, UI) from the code that performs it.
  • Commands are data: they can be queued, delayed, serialized, logged or replayed.

− Disadvantages

  • Each action needs its own class, which can mean a lot of small files.
  • Undo must restore state exactly; commands that touch physics, randomness or other systems are hard to reverse correctly.
  • Long histories hold references to objects, so you may need to cap the stack or clear it when objects are destroyed.

Tips

  1. 01Clear the redo stack whenever a brand-new command is executed — otherwise redo can replay a branch of history that no longer makes sense.
  2. 02Store the result of an action in the command (e.g. the position before moving) so Undo does not have to recompute anything.
  3. 03Validate before executing: if a move is blocked, do not push it onto the history at all.
  4. 04For replays, record the frame number alongside each command and re-execute them in order from a known starting state.
  5. 05Keep commands plain C# classes rather than MonoBehaviours so they are cheap to allocate and easy to test.