Custom object pooling system for Unity.
Instead of constantly creating and destroying GameObjects, this system reuses inactive instances to improve runtime performance and reduce garbage collection spikes.
Attach PoolableObject to your prefab.
using ThornDuck.PoolingSystem;
using UnityEngine;
public class Bullet : PoolableObject
{
private void Awake()
=> OnRetrieveFromPool += Reset;
private void Reset()
{
// Reset state here
}
}Prewarming creates inactive instances ahead of time to avoid runtime instantiation spikes.
PoolingSystem.Prewarm(bulletPrefab, 50);PoolableObject bullet = PoolingSystem.TryGetInstance(
bulletPrefab,
spawnPosition,
spawnRotation
);If the pool is empty, the system automatically creates a new instance.
Instead of destroying objects:
PoolingSystem.ReturnInstance(bullet);The object becomes inactive and is reused later.
public class Gun : MonoBehaviour
{
[SerializeField] private PoolableObject bulletPrefab;
private void Start()
=> PoolingSystem.Prewarm(bulletPrefab, 100);
private void Shoot()
{
PoolableObject bullet = PoolingSystem.TryGetInstance(
bulletPrefab,
transform.position,
transform.rotation
);
if (bullet == null)
return;
}
}The system includes built-in safety limits (max number of pools, max number of instances and max instances per prefab). If limits are exceeded, the oldest unused pool is automatically removed and instance creation safely fails.
Warning
Never use Destroy() on pooled instances directly, use PoolingSystem.ReturnInstance() instead.
However, if a pooled object is destroyed manually, the system automatically deregisters it safely.