←All patterns
Behavioral

Memento

Capture an object’s state in a sealed snapshot so it can be restored later without exposing its internals.

What Is It?

The Memento pattern has three roles. The originator is the object whose state matters (a Player). The memento is an immutable snapshot of that state. The caretaker stores mementos and hands one back when asked, but never looks inside.

The key idea is encapsulation: only the originator knows how to build a memento from its fields and how to apply one back. A save system, checkpoint manager or rewind feature can keep dozens of snapshots without depending on what a player actually contains.

In a Unity game this looks like player.Save() returning a PlayerMemento record with position, health and level, a SaveHistory caretaker that keeps a list of them, and player.Restore(memento) snapping everything back when the player dies or loads a checkpoint.

When Is It Used?

Use it for checkpoints, quick-save/quick-load, undo in editors, or a short “rewind time” mechanic where you need to return an object to an earlier state.

It is especially useful when the state is private: the originator stays in charge of what is captured, so you do not have to add public setters just so a save system can poke at it.

Be careful with large or frequently changing state. Snapshotting a whole level every frame is expensive; store deltas, sample less often or limit the history length instead.

Interactive Demo

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

Memento Pattern
snapshots0/5state—
Scene
1
Player
Originator
health100
level1
position(0.0, 0.0)
SaveHistory · Caretakertap a card to select
No snapshots yet — press Save()
Console
Press a button to see what happens…

Code

Assets / Scripts / Behavioral/ Memento ›CheckpointTester.cs
using UnityEngine;

namespace Patterns.Behavioral.Memento
{
    /// <summary>
    /// Client: saves and loads checkpoints. It shuttles mementos
    /// between the player and the history without inspecting them.
    /// </summary>
    public class CheckpointTester : MonoBehaviour
    {
        [SerializeField] private Player player;

        private readonly SaveHistory history = new(capacity: 5);

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.F5))
            {
                PlayerMemento snapshot = player.Save();
                history.Push(snapshot);
                Debug.Log($"Saved {snapshot}");
            }

            if (Input.GetKeyDown(KeyCode.F9) && history.Latest != null)
            {
                player.Restore(history.Latest);
                Debug.Log($"Restored {history.Latest}");
            }

            // Mess with the state so there is something to restore.
            if (Input.GetKeyDown(KeyCode.D)) player.TakeDamage(25);
            if (Input.GetKeyDown(KeyCode.L)) player.LevelUp();
            if (Input.GetKeyDown(KeyCode.M)) player.Move(Random.insideUnitSphere * 3f);
        }
    }
}
4 files · namespace Patterns.Behavioral.MementoC# · UTF-8 · LF

Before & After

Real-world smell: a player that keeps its own single checkpoint. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

Player mirrors its state into private savedPosition, savedHealth and savedLevel fields, and SaveCheckpoint/LoadCheckpoint copy values back and forth.

There is exactly one slot hidden inside the player, so you cannot keep several checkpoints, write one to disk, or let a rewind system hold history. Every new field (mana, inventory) has to be added in three places, and forgetting one means a load quietly restores only half the state.

✓ What changed

  • The four saved*/hasCheckpoint fields are gone; the player no longer stores any history itself.
  • SaveCheckpoint becomes Save(), which returns an immutable PlayerMemento instead of writing into hidden fields.
  • LoadCheckpoint becomes Restore(PlayerMemento), so any snapshot can be applied, not only the last one.
  • Where snapshots live is now the caller’s choice: SaveHistory keeps several, and the same memento could be serialized to a save file.
Player.Before.cs → Player.After.cs+8/−19
11 using UnityEngine;
22
33 namespace Patterns.Behavioral.Memento
44 {
55 /// <summary>
6− /// Without Memento: the player mirrors its own fields into a single
7− /// built-in checkpoint slot.
6+ /// With Memento: the player packs its state into an immutable snapshot
7+ /// and applies one back. Where snapshots are kept is someone else's job.
88 /// </summary>
99 public class Player : MonoBehaviour
1010 {
1111 [SerializeField] private int maxHealth = 100;
1212
1313 private int health;
1414 private int level = 1;
1515
16− // One hidden slot. Every new field has to be copied here by hand.
17− private Vector3 savedPosition;
18− private int savedHealth;
19− private int savedLevel;
20− private bool hasCheckpoint;
21−
2216 public int Health => health;
2317 public int Level => level;
2418
2519 private void Awake() => health = maxHealth;
2620
2721 public void TakeDamage(int amount) => health = Mathf.Max(0, health - amount);
2822 public void LevelUp() => level++;
2923 public void Move(Vector3 delta) => transform.position += delta;
3024
31− public void SaveCheckpoint()
25+ public PlayerMemento Save()
3226 {
33− savedPosition = transform.position;
34− savedHealth = health;
35− savedLevel = level;
36− hasCheckpoint = true;
27+ return new PlayerMemento(transform.position, health, level);
3728 }
3829
39− public void LoadCheckpoint()
30+ public void Restore(PlayerMemento memento)
4031 {
41− if (!hasCheckpoint) return;
42−
43− transform.position = savedPosition;
44− health = savedHealth;
45− level = savedLevel;
32+ transform.position = memento.Position;
33+ health = memento.Health;
34+ level = memento.Level;
4635 }
4736 }
4837 }

Advantages & Disadvantages

+ Advantages

  • Preserves encapsulation — the caretaker treats snapshots as opaque tokens.
  • Immutable snapshots are safe to share and easy to reason about.
  • Simplifies the originator: no undo bookkeeping, just Save() and Restore().

− Disadvantages

  • Snapshots cost memory; long histories of large objects add up quickly.
  • References to other objects (targets, inventory items) are tricky to snapshot and restore correctly.
  • The caretaker cannot tell what changed between snapshots without help from the originator.

Tips

  1. 01Use a C# record or a readonly struct for the memento so nobody can mutate a saved state by accident.
  2. 02Cap the history with a ring buffer for rewind features; drop the oldest snapshot when it is full.
  3. 03For save files, serialize the memento with JsonUtility — it is already a plain data object.
  4. 04Store IDs instead of object references inside a memento, and resolve them on restore.
  5. 05Combine with Command: a command can take a memento before executing and restore it in Undo() when the action is hard to reverse by hand.