To pool standard C# classes (non-Unity objects), use ObjectPool<T>. You must provide a creation function and can optionally provide callbacks for renting, returning, and destruction.
Warning: Object pools are not thread-safe.
Key Methods:
Rent(): Retrieves an instance.Return(instance): Returns an instance to the pool.Prewarm(count): Pre-instantiates objects.Count: Gets the number of objects in the pool.Clear(): Removes all objects from the pool.Dispose(): Destroys the pool.
class PooledObject { }
var pool = new ObjectPool<PooledObject>(
createFunc: () => new PooledObject(), // How to create the object
onRent: instance => { }, // Optional: logic when rented
onReturn: instance => { }, // Optional: logic when returned
onDestroy: instance => { } // Optional: logic when pool is destroyed
);
pool.Prewarm(10);
var instance = pool.Rent();
pool.Return(instance);
var count = pool.Count;
pool.Clear();
pool.Dispose();