CREATIONAL

Prototype

What is it?

Prototype is a design pattern that lets you create new objects by copying an existing template object instead of building everything from scratch. The main idea is simple: prepare one well-configured object, then clone it whenever you need a new version.

This is useful when an object has a complex starting setup. For example, an enemy may already have health, speed, damage values, abilities, and references prepared in advance.

The most important detail is how the copy is made. A shallow copy may still share some references with the original object. A deep copy creates independent copies of internal data as well.

When is it used?

Prototype is useful when creating an object from zero is expensive or repetitive. If an object needs many values, references, or setup steps before it is ready, cloning an already prepared version is usually cleaner.

It also works well when many variations come from the same base object. For example, you can create a basic enemy data object, clone it, then slightly change its health, speed, or damage for different waves.

In Unity, it is especially useful with ScriptableObjects. Instead of modifying an editor asset directly during runtime, you clone it and apply changes to the copy.

However, Prototype is not always necessary. If an object is simple and cheap to create with new, adding a clone system may only make the code more complicated.

Animation

rule: always clone from prototype
✓ Intact

Code

Assets / Scripts / Creational / PrototypeIPrototype.cs
READ ONLY
C#
1
2
3
4
5
6
7
namespace Patterns.Creational.Prototype
{
    public interface IPrototype<T>
    {
        T Clone();
    }
}

Advantages and disadvantages

• Advantages:

  • It makes object creation faster and cleaner when setup is complex.
  • It reduces repetitive setup code.
  • Calling code does not always need to know the exact concrete type.

• Disadvantages:

  • Bad clone depth can cause shared internal data.
  • Deep cloning can become difficult with complex references.
  • Scene object references in Unity can make cloning more sensitive.

Tips

In Unity, Instantiate(prefab) already works very similarly to the Prototype pattern. A prefab acts like a prepared template, and Unity creates a copy of it when needed.

ScriptableObjects are a good choice for prototype-style data. Enemy stats, weapon settings, item data, and level configurations can be stored as ScriptableObjects.

Be careful with reference-type fields. In some cases, you may need to write a custom Clone() or DeepClone() method.

Prototype works especially well together with Object Pooling for frequently spawned objects like bullets, enemies, or effects.

Prefab Variants also follow a similar idea, but changes to the base prefab can affect its variants.