Factory Pattern
Summary
The Factory pattern is a creational design pattern that delegates object creation to a dedicated factory class or method. Callers ask the factory for an object; the factory decides which concrete type to create and returns it as an abstract type (interface or base class). This means calling code never depends on concrete implementations — only on the abstract contract.
In Unity, the pattern is useful wherever many variants of an object can be spawned at runtime: enemy types, projectile variants, UI elements, or level objects. Without a factory, Instantiate calls scattered throughout the codebase become difficult to maintain when prefab variants change (Unity Technologies, Level Up Your Code with Game Programming Patterns, see source-unity-game-programming-patterns).
Implementation
Simple factory with an interface
Define an interface that all products must implement. The factory method returns the interface type, so callers are never exposed to the concrete class.
public interface IEnemy
{
void Setup(Vector3 spawnPosition);
void Attack();
}
public class Goblin : MonoBehaviour, IEnemy
{
public void Setup(Vector3 pos) { transform.position = pos; }
public void Attack() { Debug.Log("Goblin attacks!"); }
}
public class Dragon : MonoBehaviour, IEnemy
{
public void Setup(Vector3 pos) { transform.position = pos; }
public void Attack() { Debug.Log("Dragon breathes fire!"); }
}public class EnemyFactory : MonoBehaviour
{
[SerializeField] private GameObject goblinPrefab;
[SerializeField] private GameObject dragonPrefab;
public IEnemy Create(string enemyType, Vector3 position)
{
GameObject prefab = enemyType == "dragon" ? dragonPrefab : goblinPrefab;
GameObject instance = Instantiate(prefab, position, Quaternion.identity);
IEnemy enemy = instance.GetComponent<IEnemy>();
enemy.Setup(position);
return enemy;
}
}The spawner calls factory.Create("goblin", spawnPoint) and receives an IEnemy — it never needs to know whether a Goblin or Dragon will appear.
Factory with enum
Using an enum instead of strings provides compile-time safety.
public enum EnemyType { Goblin, Dragon, Skeleton }
public IEnemy Create(EnemyType type, Vector3 position)
{
GameObject prefab = type switch
{
EnemyType.Dragon => dragonPrefab,
EnemyType.Skeleton => skeletonPrefab,
_ => goblinPrefab
};
var instance = Instantiate(prefab, position, Quaternion.identity);
var enemy = instance.GetComponent<IEnemy>();
enemy.Setup(position);
return enemy;
}Combining with Object Pool
The Factory pattern pairs naturally with object-pool-pattern — the factory can check a pool for an available instance before instantiating a new one, keeping the creation logic in one place.
Trade-offs
When to use:
- Multiple variants of an object exist and which one to create depends on runtime data.
- Instantiation logic is complex (requires initialisation, dependency injection, configuration).
- You want to enforce that callers depend on an abstract type, not a concrete class.
- You expect to add new product variants without modifying existing callers (Open-Closed Principle).
When not to:
- Only one concrete type exists and no variation is anticipated — a factory is unnecessary indirection.
- The object is a simple data structure with no MonoBehaviour lifecycle — a constructor is fine.
Limitations: The factory must know about all concrete types it can create, which can grow unwieldy. A more advanced variant (the Abstract Factory) addresses families of related objects but adds further complexity.
Examples
- Projectile factory: A
ProjectileFactorycreates bullets, missiles, or grenades based on the weapon type equipped. - UI panel factory: A
PanelFactoryinstantiates the correct prefab for inventory screens, dialogue boxes, or settings menus from a single method call. - Level object factory: A procedural level generator calls a
PlatformFactorywithout caring about the platform variant selected.
Related
- csharp-interfaces — the abstract contract that factory products implement
- observer-pattern — another GoF pattern from the same source
- command-pattern — GoF behavioural pattern; often used alongside factory for action creation
- unity-gamemanager-pattern — central managers often hold or are accessed by factory classes
- source-unity-game-programming-patterns — primary source