Object Pooling
A machine gun firing 15 bullets per second calls Instantiate 15 times and Destroy 15 times a second. Each Instantiate costs CPU (creating native objects, running Awake, registering colliders), and each destroyed bullet leaves garbage. A pool keeps finished objects deactivated and hands them out again instead.
Unity ships a generic pool in UnityEngine.Pool: ObjectPool<T> (plus LinkedPool<T>, and ListPool<T>/DictionaryPool<K,V> for temporary collections).
ObjectPool in Unity
using UnityEngine;
using UnityEngine.Pool;
public class BulletSpawner : MonoBehaviour
{
[SerializeField] Bullet bulletPrefab;
ObjectPool<Bullet> pool;
void Awake()
{
pool = new ObjectPool<Bullet>(
createFunc: () =>
{
Bullet b = Instantiate(bulletPrefab);
b.Pool = pool; // so the bullet can return itself
return b;
},
actionOnGet: b => b.gameObject.SetActive(true),
actionOnRelease: b => b.gameObject.SetActive(false),
actionOnDestroy: b => Destroy(b.gameObject), // when the pool is full or cleared
collectionCheck: true, // editor-only check for double release
defaultCapacity: 32,
maxSize: 200);
}
public void Fire(Vector3 position, Vector3 direction)
{
Bullet b = pool.Get();
b.Launch(position, direction);
}
}
public class Bullet : MonoBehaviour
{
public IObjectPool<Bullet> Pool { get; set; }
[SerializeField] float speed = 40f, lifetime = 2f;
float dieAt;
Vector3 velocity;
public void Launch(Vector3 position, Vector3 direction)
{
transform.SetPositionAndRotation(position, Quaternion.LookRotation(direction));
velocity = direction.normalized * speed;
dieAt = Time.time + lifetime; // reset ALL state: this object was used before
}
void Update()
{
transform.position += velocity * Time.deltaTime;
if (Time.time >= dieAt) Pool.Release(this); // instead of Destroy(gameObject)
}
void OnTriggerEnter(Collider other) => Pool.Release(this);
}The collection pools are handy for temporary lists without garbage:
using (ListPool<Collider>.Get(out List<Collider> nearby))
{
// fill and use "nearby"; it returns to the pool at the end of the block
}How the pool works: a model
The model reimplements the parts of ObjectPool<T> that matter, with the same parameter names, and runs a burst of shooting. It counts how many objects were created, reused and destroyed:
using System;
using System.Collections.Generic;
int created = 0;
var pool = new ObjectPool<Bullet>(
createFunc: () => new Bullet(++created),
actionOnGet: b => b.Active = true,
actionOnRelease: b => b.Active = false,
actionOnDestroy: b => Console.WriteLine(quot; destroy bullet #{b.Id} (pool full)"),
collectionCheck: true, defaultCapacity: 4, maxSize: 3);
var flying = new List<Bullet>();
for (int frame = 1; frame <= 6; frame++)
{
int shots = frame <= 2 ? 3 : 1; // a burst, then steady fire
for (int i = 0; i < shots; i++) flying.Add(pool.Get());
// bullets live two frames: release the oldest when more than 2 frames' worth are out
while (flying.Count > (frame <= 2 ? 4 : 2)) { pool.Release(flying[0]); flying.RemoveAt(0); }
Console.WriteLine(quot;frame {frame}: active {pool.CountActive}, inactive {pool.CountInactive}, created so far {pool.CountAll}");
}
try { var b = pool.Get(); pool.Release(b); pool.Release(b); }
catch (InvalidOperationException e) { Console.WriteLine(quot;double release: {e.Message}"); }
class Bullet { public int Id; public bool Active; public Bullet(int id) => Id = id; }
class ObjectPool<T> where T : class
{
readonly Stack<T> inactive;
readonly Func<T> createFunc;
readonly Action<T>? onGet, onRelease, onDestroy;
readonly bool collectionCheck;
readonly int maxSize;
public int CountAll { get; private set; }
public int CountInactive => inactive.Count;
public int CountActive => CountAll - CountInactive;
public ObjectPool(Func<T> createFunc, Action<T>? actionOnGet = null, Action<T>? actionOnRelease = null,
Action<T>? actionOnDestroy = null, bool collectionCheck = true, int defaultCapacity = 10, int maxSize = 10000)
{
this.createFunc = createFunc; onGet = actionOnGet; onRelease = actionOnRelease; onDestroy = actionOnDestroy;
this.collectionCheck = collectionCheck; this.maxSize = maxSize;
inactive = new Stack<T>(defaultCapacity);
}
public T Get()
{
T item;
if (inactive.Count == 0) { item = createFunc(); CountAll++; }
else item = inactive.Pop();
onGet?.Invoke(item);
return item;
}
public void Release(T item)
{
if (collectionCheck && inactive.Contains(item))
throw new InvalidOperationException("Trying to release an object that has already been released to the pool.");
onRelease?.Invoke(item);
if (inactive.Count < maxSize) inactive.Push(item);
else { CountAll--; onDestroy?.Invoke(item); }
}
}frame 1: active 3, inactive 0, created so far 3
frame 2: active 4, inactive 2, created so far 6
destroy bullet #5 (pool full)
frame 3: active 2, inactive 3, created so far 5
frame 4: active 2, inactive 3, created so far 5
frame 5: active 2, inactive 3, created so far 5
frame 6: active 2, inactive 3, created so far 5
double release: Trying to release an object that has already been released to the pool.
The burst creates a few objects, then steady fire reuses them. maxSize caps the inactive objects, not the total: when the pool is full, a released object is destroyed instead of kept. Unity's real exception message for a double release is almost the same as the model's.
Pooling pitfalls
- Reset all state on
Get(or in yourLaunch/Initmethod): health, velocity, timers, trails (TrailRenderer.Clear()), particle systems (Clear()+Play()), Rigidbody velocity, coroutines. - Never
Destroya pooled object from outside the pool, and never use it afterRelease. KeepcollectionCheckon during development. OnEnable/OnDisablerun on everyGet/Releasebecause the object is activated and deactivated;AwakeandStartonly once. Put per-use initialization inOnEnableor an explicit method.- Prewarm during a loading screen:
Getthe expected number andReleasethem right away, so the first firefight doesn't create objects mid-game. - Don't pool everything. Objects created a few times per level aren't worth the complexity.
Test yourself
What does maxSize limit in Unity's ObjectPool<T>?
- The total number of objects ever created
- How many inactive objects the pool keeps; extras are destroyed on release
- The number of Get calls per frame
- The number of active objects
Which lifecycle method runs every time a pooled GameObject is taken from the pool with SetActive(true)?
- Awake
- Start
- OnEnable
- OnDestroy
What does collectionCheck: true protect against?
- Memory leaks in textures
- Releasing the same object twice
- Getting null objects
- Pool overflow