Command pattern undo

From nlelouche/Unity-SkillForge · View interactive version

Command pattern undo is an AI agent skill from the GitHub repository nlelouche/Unity-SkillForge. Implements the Command Pattern with a full undo/redo history stack. Applicable to editor tools, strategy game moves, crafting systems, or any operation that must be reversible.

How to use this skill

Skill file

Command Pattern + Undo/Redo

Overview

The Command Pattern encapsulates an operation as an object, decoupling the invoker (button, hotkey) from the receiver (game state). When combined with a history stack, you get full undo/redo. Use it for custom editor tools (Ctrl+Z), strategy game moves ("take back"), level designers, or any gameplay system requiring reversible operations.

When to Use

Architecture

┌───────────────────────────────────────────────────────────────┐
│                  COMMAND PATTERN + HISTORY                    │
├───────────────────────────────────────────────────────────────┤
│                                                               │
│  INVOKER                    HISTORY STACK                     │
│  ┌────────────────┐         ┌───────────────────────────┐    │
│  │ UI Button      │─Execute─▶ CommandHistory             │    │
│  │ Hotkey Handler │         │  Stack<ICommand> _undo    │    │
│  │ AI Decision    │◀─Undo───│  Stack<ICommand> _redo    │    │
│  └────────────────┘         └───────────────────────────┘    │
│                                        │                      │
│                           ┌────────────▼───────────────┐     │
│                           │        ICommand             │     │
│                           │  Execute()                  │     │
│                           │  Undo()                     │     │
│                           └────────────────────────────┘     │
│                                        │                      │
│              ┌─────────────────────────┼──────────────────┐  │
│              ▼                         ▼                   ▼  │
│   ┌───────────────────┐  ┌───────────────────┐  ┌──────────┐│
│   │PlaceBuildingCommand│  │DestroyUnitCommand │  │MoveCmd  ││
│   └───────────────────┘  └───────────────────┘  └──────────┘│
└───────────────────────────────────────────────────────────────┘

TDD Contract

[Test]
public void Command_Execute_AppliesStateChange()
{
    var inventory = new Inventory();
    var cmd = new AddItemCommand(inventory, new Item("Sword"));

    cmd.Execute();

    Assert.AreEqual(1, inventory.ItemCount);
}

[Test]
public void Command_Undo_RevertsStateChange()
{
    var inventory = new Inventory();
    var cmd = new AddItemCommand(inventory, new Item("Sword"));

    cmd.Execute();
    cmd.Undo();

    Assert.AreEqual(0, inventory.ItemCount);
}

[Test]
public void CommandHistory_Undo_RestoresPreviousState()
{
    var history = new CommandHistory();
    var inventory = new Inventory();

    history.Execute(new AddItemCommand(inventory, new Item("Shield")));
    history.Undo();

    Assert.AreEqual(0, inventory.ItemCount);
}

Core Implementation

// --- ICommand.cs ---
public interface ICommand
{
    void Execute();
    void Undo();
}

// --- CommandHistory.cs ---
using System.Collections.Generic;

public class CommandHistory
{
    private readonly Stack<ICommand> _undoStack = new();
    private readonly Stack<ICommand> _redoStack = new();

    public void Execute(ICommand command)
    {
        command.Execute();
        _undoStack.Push(command);
        _redoStack.Clear(); // New command clears redo history
    }

    public void Undo()
    {
        if (_undoStack.Count == 0) return;
        var command = _undoStack.Pop();
        command.Undo();
        _redoStack.Push(command);
    }

    public void Redo()
    {
        if (_redoStack.Count == 0) return;
        var command = _redoStack.Pop();
        command.Execute();
        _undoStack.Push(command);
    }

    public bool CanUndo => _undoStack.Count > 0;
    public bool CanRedo => _redoStack.Count > 0;
}

// --- Example: PlaceBuildingCommand.cs ---
public class PlaceBuildingCommand : ICommand
{
    private readonly BuildingGrid _grid;
    private readonly Vector2Int   _cell;
    private readonly BuildingType _type;
    private GameObject            _instance;

    public PlaceBuildingCommand(BuildingGrid grid, Vector2Int cell, BuildingType type)
    {
        _grid = grid;
        _cell = cell;
        _type = type;
    }

    public void Execute()
    {
        _instance = _grid.PlaceBuilding(_cell, _type);
    }

    public void Undo()
    {
        _grid.RemoveBuilding(_cell);
        Object.Destroy(_instance);
        _instance = null;
    }
}

Wiring in MonoBehaviour

public class LevelEditorController : MonoBehaviour
{
    private readonly CommandHistory _history = new();

    private void Update()
    {
        // Ctrl+Z / Ctrl+Y
        if (Input.GetKeyDown(KeyCode.Z) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.LeftCommand)))
            _history.Undo();

        if (Input.GetKeyDown(KeyCode.Y) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.LeftCommand)))
            _history.Redo();
    }

    public void OnPlaceBuilding(Vector2Int cell, BuildingType type)
    {
        _history.Execute(new PlaceBuildingCommand(_buildingGrid, cell, type));
    }
}

Best Practices

Related Skills

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.