Unity Object Pool Generator
Generate a Unity pooling class with configurable capacity, optional callbacks and timed returns.
Object pooling reuses instances to reduce repeated creation, destruction and allocation costs. Generate a starting implementation, then profile it with your prefabs and spawning patterns.
Configuration
Generated Code
Uses UnityEngine.Pool.ObjectPool<T>, available in Unity 2021.1 and later.
using UnityEngine;
using UnityEngine.Pool;
using System.Collections.Generic;
public class ProjectilePool : MonoBehaviour
{
[SerializeField] private GameObject prefab;
[SerializeField] private int initialSize = 20;
private ObjectPool<GameObject> pool;
private void Awake()
{
pool = new ObjectPool<GameObject>(
createFunc: () => Instantiate(prefab),
actionOnGet: obj => obj.SetActive(true),
actionOnRelease: obj => obj.SetActive(false),
actionOnDestroy: obj => Destroy(obj),
defaultCapacity: 20,
maxSize: 100
);
// Pre-warm the pool
var prewarm = new GameObject[initialSize];
for (int i = 0; i < initialSize; i++)
{
prewarm[i] = pool.Get();
}
for (int i = 0; i < initialSize; i++)
{
pool.Release(prewarm[i]);
}
}
public GameObject Get()
{
GameObject obj = pool.Get();
return obj;
}
public GameObject Get(Vector3 position, Quaternion rotation)
{
GameObject obj = Get();
obj.transform.SetPositionAndRotation(position, rotation);
return obj;
}
public void Release(GameObject obj)
{
if (obj == null) return;
pool.Release(obj);
}
}Usage Example
How to use the generated pool in your game scripts.
// Getting an object from the pool
[SerializeField] private ProjectilePool pool;
GameObject projectile = pool.Get(transform.position, transform.rotation);
// Returning it when done
pool.Release(projectile);UnityEngine.Pool.ObjectPool vs custom pool
Unity 2021.1 added a built-in object pool. Here is when each approach is the right call.
| UnityEngine.Pool.ObjectPool | Custom pool | |
|---|---|---|
| Available since | Unity 2021.1 | Any version |
| Setup | Generic API, simple | More code, more flexibility |
| Inspector visibility | None | Possible with serialised fields |
| Cross-scene sharing | No | Yes if you build it |
| Best for | Bullets, particles, simple cases | Singletons, scene-shared pools |
Related Tools
Coroutine vs Async
Side-by-side comparison of Unity coroutines and async/await with code for every common pattern.
Scripting Order
Interactive Unity MonoBehaviour lifecycle diagram. When does Awake, Start, Update, and every callback run.
DOTween Reference
Searchable DOTween cheat sheet with copy-paste Unity C# code for every common tween method.
Git for Game Dev
.gitignore templates for Unity, Unreal, and Godot, Git LFS setup, and team workflows. The Unity template is explained block by block.
Frequently asked questions
When should I use object pooling in Unity?
Should I use Unity ObjectPool or a custom pool?
How big should my object pool be?
How do I reset a pooled object before reuse?
Last updated: