←All patterns
Creational

Factory

Hide which concrete class gets created behind a single method that returns an interface.

What Is It?

A Factory centralises object creation. Clients ask for "a Goblin" through a method like Create(EnemyType.Goblin) and receive an IEnemy back; they never write new Goblin() or reference the Goblin prefab themselves.

Because the client only knows the interface, you can add a Dragon, swap the Orc prefab or route creation through an object pool without touching any spawner, wave controller or debug tool that calls the factory.

In Unity the factory usually owns a lookup of prefabs — often a ScriptableObject with a list of (EnemyType, prefab) entries — and calls Instantiate plus any post-setup (stats, team, difficulty scaling) in one place.

When Is It Used?

Use it when several systems create the same family of objects: wave spawners, a level editor, cheat menus and save-game loading all need "make me enemy X".

It is valuable when creation involves more than Instantiate — injecting dependencies, applying difficulty multipliers, registering with a manager — and you do not want that logic copy-pasted.

Do not bother for one-off objects only ever created in one spot. A serialized prefab reference and Instantiate is clearer.

Interactive Demo

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

Factory Pattern
alive0created0in flight0
Spawner
uses IEnemy
EnemyFactory
ScriptableObject
prefabs
Goblin
Orc
Dragon
Arena · List<IEnemy>
no enemies yet
Console
Press a button to see what happens…

Code

Assets / Scripts / Creational/ Factory ›EnemySpawner.cs
using System.Collections.Generic;
using UnityEngine;

namespace Patterns.Creational.Factory
{
    /// <summary>
    /// Client. It knows enemy *types* and the factory, but never
    /// references Goblin, Orc or Dragon classes or prefabs.
    /// </summary>
    public class EnemySpawner : MonoBehaviour
    {
        [SerializeField] private EnemyFactory factory;
        [SerializeField] private Transform[] spawnPoints;

        private readonly List<IEnemy> alive = new();

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.Alpha1)) Spawn(EnemyType.Goblin);
            if (Input.GetKeyDown(KeyCode.Alpha2)) Spawn(EnemyType.Orc);
            if (Input.GetKeyDown(KeyCode.Alpha3)) Spawn(EnemyType.Dragon);

            if (Input.GetKeyDown(KeyCode.Space))
                foreach (IEnemy enemy in alive)
                    enemy.Attack();
        }

        private void Spawn(EnemyType type)
        {
            Transform point = spawnPoints[Random.Range(0, spawnPoints.Length)];
            IEnemy enemy = factory.Create(type, point.position, transform);

            if (enemy != null)
                alive.Add(enemy);
        }
    }
}
4 files · namespace Patterns.Creational.FactoryC# · UTF-8 · LF

Before & After

Real-world smell: a spawner that references every enemy prefab. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

EnemySpawner has a serialized field each for Goblin, Orc and Dragon, and a switch that maps each EnemyType to its prefab before calling Instantiate.

The wave controller and the boss room need enemies too, so the same fields and switch are copied there. Adding an enemy means editing every copy, and an unassigned prefab only shows up as a NullReferenceException the first time that enemy spawns.

✓ What changed

  • The three prefab fields and the switch are replaced by one EnemyFactory asset.
  • Spawn calls factory.Create(type, point.position, transform) and gets back an IEnemy, never a concrete class.
  • The type-to-prefab table lives in the factory asset, so a new enemy is a new entry there and no spawner changes.
  • A missing prefab is reported inside the factory with a clear error, and the spawner simply skips a null result.
EnemySpawner.Before.cs → EnemySpawner.After.cs+8/−19
11 using System.Collections.Generic;
22 using UnityEngine;
33
44 namespace Patterns.Creational.Factory
55 {
66 /// <summary>
7− /// Without Factory: the spawner references every concrete enemy prefab
8− /// and picks one with a switch.
7+ /// With Factory: the spawner knows enemy types and one factory asset.
8+ /// Which prefab backs each type is decided in the factory.
99 /// </summary>
1010 public class EnemySpawner : MonoBehaviour
1111 {
12− [SerializeField] private Goblin goblinPrefab;
13− [SerializeField] private Orc orcPrefab;
14− [SerializeField] private Dragon dragonPrefab;
12+ [SerializeField] private EnemyFactory factory;
1513 [SerializeField] private Transform[] spawnPoints;
1614
17− private readonly List<Enemy> alive = new();
15+ private readonly List<IEnemy> alive = new();
1816
1917 private void Update()
2018 {
2119 if (Input.GetKeyDown(KeyCode.Alpha1)) Spawn(EnemyType.Goblin);
2220 if (Input.GetKeyDown(KeyCode.Alpha2)) Spawn(EnemyType.Orc);
2321 if (Input.GetKeyDown(KeyCode.Alpha3)) Spawn(EnemyType.Dragon);
2422
2523 if (Input.GetKeyDown(KeyCode.Space))
26− foreach (Enemy enemy in alive)
24+ foreach (IEnemy enemy in alive)
2725 enemy.Attack();
2826 }
2927
3028 private void Spawn(EnemyType type)
3129 {
3230 Transform point = spawnPoints[Random.Range(0, spawnPoints.Length)];
3331
34− // The wave controller and the boss room have their own copy of this switch.
35− Enemy prefab = type switch
36− {
37− EnemyType.Goblin => goblinPrefab,
38− EnemyType.Orc => orcPrefab,
39− EnemyType.Dragon => dragonPrefab,
40− _ => null,
41− };
42−
43− Enemy enemy = Instantiate(prefab, transform);
44− enemy.Spawn(point.position);
45− alive.Add(enemy);
32+ IEnemy enemy = factory.Create(type, point.position, transform);
33+ if (enemy != null)
34+ alive.Add(enemy);
4635 }
4736 }
4837 }

Advantages & Disadvantages

+ Advantages

  • Clients depend on IEnemy, not concrete classes — low coupling.
  • One place to add new types, change prefabs or plug in pooling.
  • Data-driven: designers can register new prefabs in a ScriptableObject without code changes.

− Disadvantages

  • Adds an indirection layer; jumping to "where is this created?" takes an extra hop.
  • A giant switch in the factory can become its own maintenance hotspot if not data-driven.
  • Type keys (enums or strings) can drift out of sync with registered prefabs and fail at runtime.

Tips

  1. 01Back the factory with a Dictionary<EnemyType, Enemy> built once in Awake from a serialized list — lookups stay O(1) and Inspector-editable.
  2. 02Have Create return the interface (IEnemy) so callers cannot reach into concrete-type details.
  3. 03Combine with Object Pooling: the factory can fetch from a UnityEngine.Pool.ObjectPool<T> instead of instantiating each time.
  4. 04Log a clear error (and return null) when a key has no prefab, rather than throwing deep inside a spawner.
  5. 05For families of related objects (e.g. forest vs desert enemy sets) graduate to an Abstract Factory with one factory per theme.