Object Pool

It is a relatively expensive operation to instantiate and destroy objects. To avoid many instantiations and destructions an object pool is used which will reuse an already-created object. The ObjectPool component can pool both GameObjects and regular objects derived from System.object.

When a new object is instantiated the ObjectPool.Instantiate method is called instead of the GameObject.Instantiate method. An object can then be placed back in the pool with ObjectPool.Destroy.

Consider the following example where a projectile is spawned. Instead of using GameObject.Instantiate/Destroy you want to use the ObjectPool component to improve performance. The following code can be used:

// Include the namespace that the ObjectPool component is located in.
using Opsive.Shared.Game;

// Keep a reference to the object so it can later be destroyed.
private GameObject m_Projectile;

// Instantiate the projectile.
m_Projectile = ObjectPool.Instantiate(projectilePrefab);

// The projectile should be destroyed at a later point in time.
ObjectPool.Destroy(m_Projectile);

The GenericObjectPool can also pool non-GameObjects with the Get and Return methods. The following example shows the ActiveInputEvent object being pooled (ActiveInputEvent is derived from System.object):

// Include the namespace that the GenericObjectPool component is located in.
using Opsive.Shared.Utility;

// Keep a reference to the object so it can later be destroyed.
private ActiveInputEvent m_PooledInputEvent;

// Get a new ActiveInputEvent object.
m_PooledInputEvent = GenericObjectPool.Get<ActiveInputEvent>();

// The object can be returned back to the pool at a later point in time.
GenericObjectPool.Return(m_PooledInputEvent);