Learning about software patterns can be confusing for beginners. You might understand the pattern but you’re not sure what to use it for. In this overview, we will show you several real world examples of how you can use the Factory Pattern in Unity


The Factory Pattern
The Factory Pattern is a Design Pattern to create objects while also hiding their creation logic. As a result, the creation of an object becomes the single responsibility of the Factory Class.. Next, it creates more abstract code since only the Factory knows about the creation logic.
A commonly used Factory Pattern in Unity is the GameObject.Instantiate() method. through which we instantiate prefabs. If you want to read more about abstraction we recommend reading our article about it.
Factory Pattern Examples in Unity
Static Factory Method
The first example of a factory pattern in Unity is through a static factory method. In the code below, we have created a Factory class that spawns a red sphere whenever we call the Create method. Important to note is that the code calling the Create method has no idea on how the sphere is spawned. This again enforces abstraction in our code.
public static class Factory { public static GameObject Create() { GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); sphere.GetComponent<Renderer>().material.color = Color.red; return sphere; } }
Simple MonoBehaviour Factory
Of course, since we are working with Unity, we can also use a MonoBehaviour as a Factory base class. This has the added advantage that we can use our factory with the Unity Inspector. In the following example, we have created an ExplosionFactory class that instantiates prefabs at a specified position.
ExplosionFactory.cs
using UnityEngine; public class ExplosionFactory : MonoBehaviour { [SerializeField] private GameObject explosionPrefab; public GameObject Create(Vector3 position) { return Instantiate(explosionPrefab, position, Quaternion.identity); } }
Using the ExplosionFactory class, we can create explosions anywhere in our game in a uniform way. In the code below, you can see how a Bullet class spawns an explosion whenever it hits something. Yet, we could also use the ExplosionFactory class whenever the player takes damage or an enemy dies.
Bullet.cs
using UnityEngine; public class Bullet : MonoBehaviour { [SerializeField] private ExplosionFactory explosionFactory; private void OnCollisionEnter(Collision collision) { // Create an explosion on impact. explosionFactory.Create(transform.position); } }
Generic Factory
The next example of a factory pattern is a Generic Factory that uses a C# generic argument. This factory class instantiates a new prefab whenever we call the Create method.
GenericsFactory.cs
using UnityEngine; public class GenericFactory<T> : MonoBehaviour where T : MonoBehaviour { [SerializeField] private T original; public virtual T Create() { return Instantiate(original); } }
Using our new GenericFactory class, we can derive a new class that automatically inherits its Create method.. Because we are using generics, we can replace the generic parameter T with any type we want. For example, using our GenericFactory class, we can create an enemy spawner class.
EnemySpawner.cs
public class EnemySpawner : GenericFactory<Enemy> { }
Generic ScriptableObject Factory
Of course, we can also choose to implement our factory using a ScriptableObject. Similar to the Generic Factory class, we can assign the original prefab through the Unity inspector.
In the following example, you can see how we have implemented an EnemySpawner that acts as a factory. This factory class instantiates new enemies whenever we call its Create method.
GenericScriptableObjectFactory.csEnemySpawner.cs
using UnityEngine; public class GenericScriptableObjectFactory<T> : ScriptableObject where T : MonoBehaviour { [SerializeField] private T original; public virtual T Create() { return Instantiate(original); } }
[CreateAssetMenu(menuName = "Factories/Enemy Spawner")] public class EnemySpawner : GenericScriptableObjectFactory<Enemy> { }
Real World Factory Pattern Examples in Unity
Spawning Bullets in Unity
A more complex example of a real world factory pattern in Unity is that of spawning bullets. In this example, we will spawn bullets based on the player level. Using the player level, we are able to determine an upgrade level and modify the bullet accordingly. In our example, the higher the player level, the more damage the bullet does and the larger it is.
Again, the code that calls the Create method is fully unaware on how to create the bullet. Nor does it have any idea that there are different damage levels or that the bullet grows in size.
BulletFactory.cs
using UnityEngine; public class BulletFactory : MonoBehaviour { [SerializeField] private Bullet original; [SerializeField] private Player player; public Bullet Create() { // Create a new bullet Bullet bullet = Instantiate<Bullet>(original); // Use the player level as upgrade level int upgradeLevel = player.GetLevel() + 1; // Set damage and size according to the upgrade level. bullet.SetDamage(upgradeLevel); bullet.transform.localScale *= upgradeLevel; // Inherit the direction from the player. bullet.transform.forward = player.transform.forward; return bullet; } }
Spawning Random Items in Unity
Another example of how we can use a Factory Pattern in Unity is through loot drops. Below you can see an implementation of a LootFactory which spawns an item near the player. During the spawn, the factory selects a randomly chosen item from a set of predetermined items. Next, there is a random chance that the item gets a legendary status.
LootFactory.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LootFactory : MonoBehaviour { [SerializeField] private List<Item> originalSet; [SerializeField] private Player player; public Item Create() { // Choose a random item Item chosenItem = originalSet[Random.Range(0, originalSet.Count-1)]; // Spawn the chosen item near the player Item item = Instantiate<Bullet>(chosenItem, player.transform.position, Quaternion.Identity); // Randomly give an item Legendary status. if(Random.Rnage(0, 10) > 8) { item.SetLegendary(true); } return item; } }
Spawning Enemies in Unity Using a Pool
Our final example spawns enemies using a Factory Pattern in a very special way. This factory uses a pool which holds already created enemies. Instead of instantiating a new Enemy, it will re-use an already existing one..
Reusing objects is usually referred to as pooling., Through pooling, we reduce the amount of objects we are creating (dynamic allocation) at runtime. As a result, the game will run faster at the cost of more memory usage.
EnemyFactory.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyFactory : MonoBehaviour { [SerializeField] private Enemy original; [SerializeField] private int poolSize = 10; private List<Enemy> pool; private List<Enemy> active; private void Awake() { pool = new List<Enemy>(); active = new List<Enemy>(); // Fill the pool with enemies for(int i = 0; i < poolSize; i ++) { pool.Add(AllocateEnemy()); } } private void Update() { ManagePool(); } public Enemy Create() { // Allocate an extra enemy if the pool has no enemies left if(pool.Count == 0) { pool.Add(AllocateEnemy()); Debug.LogWarning("Allocated one enemy to the pool since it was empty!"); } // Get the first enemy and set it up Enemy enemy = pool[0]; enemy.gameObject.SetActive(true); enemy.SetAlive(true); // Move the enemy from the pool to the active enemies. pool.RemoveAt(0); active.Add(enemy); return enemy; } private void ManagePool() { // Determine if any of the active enemies has died for(int i = active.Count-1; i >= 0; i --) { Enemy enemy = active[i]; if(enemy.IsAlive() == false) { // Deactiate the enmy and move it back to the pool. enemy.gameObject.SetActive(false); active.RemoveAt(i); pool.Add(enemy); } } } private Enemy AllocateEnemy() { Enemy enemy = Instantiate<Enemy>(original); enemy.gameObject.SetActive(false); // Disable an enemy since it's in the pool. return enemy; } }
Summary
What you learned in this article:
- The Factory Pattern is a Design Pattern to create objects while also hiding their creation logic
- You have seen several examples of what to use the Factory Pattern for
- A factory can use pooling to improve performance by reducing dynamic allocations

Conclusion
To conclude, we hope you now have a better intuitive understanding of the Factory Pattern and how to use it in Unity. In this overview, we have shown how to use the Factory Pattern and several real world examples. If you found this article helpful, please share it.
Further Reading
Other articles you may find interesting:
