←All patterns
Creational

Prototype

Create new objects by copying a configured example instead of building each one from scratch.

What Is It?

With the Prototype pattern you set up one object exactly the way you want — colour, size, stats, loadout — and then produce new objects by cloning it. The clone starts as a copy and can be tweaked independently.

The subtle part is shallow vs deep copying. MemberwiseClone() copies fields one by one: value types are duplicated, but reference types such as a List<string> of abilities are shared. Mutate the list on a clone and every sibling (and the prototype) sees the change. A deep clone duplicates those inner objects too.

Unity already ships the most famous prototype implementation: Instantiate(original). Every prefab is a prototype, and instantiating a configured scene object copies its whole hierarchy and serialized fields. For plain C# data you implement cloning yourself.

When Is It Used?

Use it when an object is expensive or fiddly to configure and you need many similar copies: a tuned elite enemy, a bullet with modifiers, a procedurally generated item to duplicate.

It is a natural fit for "spawn more like this" mechanics — splitting slimes, mirror images, copy/paste in a level editor — where the source object is chosen at runtime.

Avoid hand-written cloning for deep, cyclic object graphs; it is easy to miss a field. Prefer serialisation-based copies or redesign towards immutable data.

Interactive Demo

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

Prototype Pattern
modedeepclones0sharing proto list0
Prototype
Clones
prototype
hp 30 · ×1.00
abilities → list#1
Bounce
Console
Press a button to see what happens…

Code

Assets / Scripts / Creational/ Prototype ›CloneSpawner.cs
using UnityEngine;

namespace Patterns.Creational.Prototype
{
    /// <summary>
    /// Client. Uses Instantiate (Unity's built-in prototype) for the
    /// GameObject, and EnemyData.Clone() for its plain C# data.
    /// </summary>
    public class CloneSpawner : MonoBehaviour
    {
        [SerializeField] private GameObject prototypeObject; // a configured scene object or prefab
        [SerializeField] private EnemyData prototypeData = new();
        [SerializeField] private float spread = 3f;

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.C))
                SpawnClone();
        }

        private void SpawnClone()
        {
            Vector3 offset = Random.insideUnitSphere * spread;
            offset.y = 0f;

            // 1. Unity copies the whole hierarchy and serialized fields.
            GameObject go = Instantiate(prototypeObject, transform.position + offset, Quaternion.identity);
            go.transform.localScale = Vector3.one * prototypeData.size;

            // 2. Our own deep copy for runtime data.
            EnemyData data = prototypeData.Clone();
            data.abilities.Add("Split"); // safe: prototype's list is untouched

            if (go.TryGetComponent(out Renderer r))
                r.material.color = data.color;

            Debug.Log($"Clone: {data}");
            Debug.Log($"Prototype: {prototypeData}");
        }
    }
}
3 files · namespace Patterns.Creational.PrototypeC# · UTF-8 · LF

Before & After

Real-world smell: a spawner that rebuilds enemies in code and copies data by hand. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

SpawnClone creates a sphere with CreatePrimitive, adds components one by one, and builds a new EnemyData by copying each field from prototypeData.

Anything configured in the editor (child objects, colliders, particle effects) has to be repeated in code. Worse, abilities is copied as a reference, so adding "Split" to the clone also changes the prototype, and every later clone inherits the bug.

✓ What changed

  • The CreatePrimitive/AddComponent setup is replaced by Instantiate(prototypeObject), which copies a configured object with its whole hierarchy.
  • The field-by-field initializer is replaced by prototypeData.Clone(), so the copy logic lives inside EnemyData.
  • Clone() creates a new abilities list, so changing a clone no longer touches the prototype.
  • A new value field on EnemyData is copied automatically by MemberwiseClone; only new collections need a line in Clone().
CloneSpawner.Before.cs → CloneSpawner.After.cs+8/−18
11 using UnityEngine;
22
33 namespace Patterns.Creational.Prototype
44 {
55 /// <summary>
6− /// Without Prototype: each spawn rebuilds the object from code and
7− /// copies the data field by field.
6+ /// With Prototype: the object is copied from a configured original,
7+ /// and the data copies itself deeply with Clone().
88 /// </summary>
99 public class CloneSpawner : MonoBehaviour
1010 {
11− [SerializeField] private Material slimeMaterial;
11+ [SerializeField] private GameObject prototypeObject; // a configured scene object or prefab
1212 [SerializeField] private EnemyData prototypeData = new();
1313 [SerializeField] private float spread = 3f;
1414
1515 private void Update()
1616 {
1717 if (Input.GetKeyDown(KeyCode.C))
1818 SpawnClone();
1919 }
2020
2121 private void SpawnClone()
2222 {
2323 Vector3 offset = Random.insideUnitSphere * spread;
2424 offset.y = 0f;
2525
26− // 1. Rebuild the object by hand. Anything set up in the editor is lost.
27− GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
28− go.transform.position = transform.position + offset;
26+ // 1. Unity copies the whole hierarchy and serialized fields.
27+ GameObject go = Instantiate(prototypeObject, transform.position + offset, Quaternion.identity);
2928 go.transform.localScale = Vector3.one * prototypeData.size;
30− go.AddComponent<Rigidbody>();
31− go.GetComponent<Renderer>().material = slimeMaterial;
3229
33− // 2. Copy the data field by field.
34− var data = new EnemyData
35− {
36− name = prototypeData.name,
37− color = prototypeData.color,
38− size = prototypeData.size,
39− health = prototypeData.health,
40− abilities = prototypeData.abilities, // same list instance!
41− };
42− data.abilities.Add("Split"); // also changes the prototype
30+ // 2. Our own deep copy for runtime data.
31+ EnemyData data = prototypeData.Clone();
32+ data.abilities.Add("Split"); // safe: prototype's list is untouched
4333
4434 if (go.TryGetComponent(out Renderer r))
4535 r.material.color = data.color;
4636
4737 Debug.Log($"Clone: {data}");
4838 Debug.Log($"Prototype: {prototypeData}");
4939 }
5040 }
5141 }

Advantages & Disadvantages

+ Advantages

  • New objects inherit a runtime-configured state without knowing how it was built.
  • Fewer subclasses: variants are just differently configured prototypes.
  • In Unity, prefabs plus Instantiate give you the pattern for free with editor tooling.

− Disadvantages

  • Shallow copies share references, causing spooky action-at-a-distance bugs.
  • Deep cloning must be kept in sync by hand whenever a new reference field is added.
  • ICloneable.Clone() returns object and does not say whether it is deep or shallow.

Tips

  1. 01Prefer a generic IPrototype<T> with T Clone() over ICloneable — it is typed and you can document that it is a deep copy.
  2. 02Start from MemberwiseClone() for the value fields, then explicitly new every collection and nested reference type.
  3. 03For MonoBehaviours, just Instantiate(configuredObject); Unity deep-copies serialized fields and child objects for you.
  4. 04Treat ScriptableObjects as shared data; if each clone needs its own mutable copy, Instantiate the ScriptableObject too.
  5. 05Write a quick test: mutate a clone and assert the prototype is unchanged — it catches shallow-copy regressions immediately.