←All patterns
Creational

Builder

Assemble a complex object one readable step at a time, then hand back the finished product.

What Is It?

The Builder pattern separates how an object is assembled from the object itself. Instead of a constructor with nine optional parameters, you call small, named steps — WithHead, WithArmor, WithWeapon — and finish with Build().

In C# builders are usually fluent: every step returns the builder, so the whole recipe reads as a single chained expression. A separate Director can store reusable recipes ("Knight", "Archer") that drive the same builder in a fixed order.

In Unity this is a natural fit for procedurally assembled characters, loot with random affixes, or dungeon rooms: the builder collects choices, validates them, and only at Build() instantiates prefabs and wires components together.

When Is It Used?

Reach for it when an object has many optional parts or settings and most combinations are valid — character customisers, weapon modding, enemy variants for a wave spawner.

It also helps when construction must happen in a particular order or must be validated before the object goes live, such as ensuring a ranged unit always has a weapon.

Skip it for simple objects with two or three fields. A plain constructor, object initialiser or a ScriptableObject preset is less ceremony.

Interactive Demo

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

Builder Pattern
steps0DEF0built0
Preview
var c = builder
.Build(position);
Add parts, or let a Director run a recipe.
Roster (built)
empty
Console
Press a button to see what happens…

Code

Assets / Scripts / Creational/ Builder ›BuilderTester.cs
using UnityEngine;

namespace Patterns.Creational.Builder
{
    /// <summary>
    /// Client: builds a custom character by hand and two presets
    /// through the director, all from the same builder instance.
    /// </summary>
    public class BuilderTester : MonoBehaviour
    {
        [SerializeField] private Character characterPrefab;
        [SerializeField] private float spacing = 2f;

        private void Start()
        {
            var builder = new CharacterBuilder(characterPrefab);
            var director = new CharacterDirector(builder);

            Character mage = builder
                .Named("Mage")
                .WithHead(HeadType.Hood)
                .WithWeapon(WeaponType.Staff)
                .WithColor(new Color(0.55f, 0.35f, 0.9f))
                .Build(Vector3.zero);

            Character knight = director.BuildKnight(Vector3.right * spacing);
            Character archer = director.BuildArcher(Vector3.right * spacing * 2f);

            Debug.Log($"{mage.DisplayName} DEF {mage.Defense}");
            Debug.Log($"{knight.DisplayName} DEF {knight.Defense}");
            Debug.Log($"{archer.DisplayName} DEF {archer.Defense}");
        }
    }
}
4 files · namespace Patterns.Creational.BuilderC# · UTF-8 · LF

Before & After

Real-world smell: a spawn helper with a long positional parameter list. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

Spawn takes a name, head, armor, weapon, tint and position as six positional arguments, and every caller repeats the full recipe for each archetype.

At the call site HeadType.Hood, ArmorType.None does not say which slot is which, and the mage has to spell out armor it does not even have. The knight and archer recipes are copied wherever characters spawn, and adding one optional part (a shield, a cape) changes every call.

✓ What changed

  • The Spawn helper and its six parameters are gone; CharacterBuilder takes one named step at a time, and skipped parts keep their defaults.
  • The mage is built with Named, WithHead, WithWeapon and WithColor, so each value is labelled where it is set.
  • The knight and archer recipes moved into CharacterDirector, so BuildKnight and BuildArcher are the one place to change them.
  • Build validates the choices and instantiates the prefab, so a new optional part is one new step that existing callers never notice.
BuilderTester.Before.cs → BuilderTester.After.cs+13/−17
11 using UnityEngine;
22
33 namespace Patterns.Creational.Builder
44 {
55 /// <summary>
6− /// Without Builder: one helper with a long positional parameter list,
7− /// and every caller repeats each archetype's full recipe.
6+ /// With Builder: named, optional steps for one-off characters, and a
7+ /// director that owns the archetype recipes in one place.
88 /// </summary>
99 public class BuilderTester : MonoBehaviour
1010 {
1111 [SerializeField] private Character characterPrefab;
1212 [SerializeField] private float spacing = 2f;
1313
1414 private void Start()
1515 {
16− Character mage = Spawn("Mage", HeadType.Hood, ArmorType.None, WeaponType.Staff,
17− new Color(0.55f, 0.35f, 0.9f), Vector3.zero);
16+ var builder = new CharacterBuilder(characterPrefab);
17+ var director = new CharacterDirector(builder);
1818
19− // Copied into the wave spawner, the arena and the debug menu too.
20− Character knight = Spawn("Knight", HeadType.Helmet, ArmorType.Plate, WeaponType.Sword,
21− new Color(0.75f, 0.8f, 0.9f), Vector3.right * spacing);
22− Character archer = Spawn("Archer", HeadType.Hood, ArmorType.Leather, WeaponType.Bow,
23− new Color(0.3f, 0.7f, 0.35f), Vector3.right * spacing * 2f);
19+ Character mage = builder
20+ .Named("Mage")
21+ .WithHead(HeadType.Hood)
22+ .WithWeapon(WeaponType.Staff)
23+ .WithColor(new Color(0.55f, 0.35f, 0.9f))
24+ .Build(Vector3.zero);
2425
26+ Character knight = director.BuildKnight(Vector3.right * spacing);
27+ Character archer = director.BuildArcher(Vector3.right * spacing * 2f);
28+
2529 Debug.Log($"{mage.DisplayName} DEF {mage.Defense}");
2630 Debug.Log($"{knight.DisplayName} DEF {knight.Defense}");
2731 Debug.Log($"{archer.DisplayName} DEF {archer.Defense}");
2832 }
29−
30− private Character Spawn(string displayName, HeadType head, ArmorType armor,
31− WeaponType weapon, Color tint, Vector3 position)
32− {
33− Character result = Instantiate(characterPrefab, position, Quaternion.identity);
34− result.Init(displayName, head, armor, weapon, tint);
35− return result;
36− }
3733 }
3834 }

Advantages & Disadvantages

+ Advantages

  • Construction code is self-documenting: .WithArmor(Plate).WithWeapon(Sword) reads like a sentence.
  • Directors turn common configurations into one-line presets, reused by spawners, editor tools and tests.
  • The product can be immutable after Build(), because all mutation happens inside the builder.

− Disadvantages

  • Adds an extra class (or two) per product type, which is noise for small objects.
  • It is easy to forget to reset a builder between uses and leak parts into the next product.
  • Required parts are not enforced by the compiler; you must validate in Build().

Tips

  1. 01Return this from every step to make the API fluent, and keep step names verb-like (WithX, AddX).
  2. 02Reset internal state at the end of Build() so the same builder instance can be reused safely by a spawner.
  3. 03Keep the builder a plain C# class; only touch Instantiate and components inside Build() so the steps are cheap and testable.
  4. 04Store Director recipes as ScriptableObjects if designers should be able to author new presets without code.
  5. 05Log an error in Build() when a required part is missing — fail at construction time, not in the middle of combat.