Object Pooling

To make your game more efficient and run smoother, you will likely want to use object pooling for objects that are often created and destroyed, such as projectiles, explosions and temporary effects. This avoids lag and unnecessary garbage collection.

Setting Up The Pool Manager

To get started, add a Pool Manager component anywhere in your scene. This is a singleton, which means there should only be one of them in the scene at any time.
The pool manager can be accessed from anywhere in the scene very easily using the 'PoolManager.Instance' reference.

Getting A Pooled Object

The easiest way to get a pooled object is to use the Pool Manager's 'Get' function and pass a prefab reference. This function will create an object pool for the prefab (if it doesn't already exist), and return one item at the specified position and rotation (there is also an optional parameter for setting the item's parent transform);
// Get a pooled object at a specified position and rotation
PoolManager.Instance.Get(myPrefab, somePosition, someRotation);
It's also possible to get a pooled object by name, if the prefab exists in a 'Resources' folder. Here's an example for a prefab named 'Projectile'.
// Get a pooled instance of the prefab named 'Projectile' in a Resources folder
PoolManager.Instance.Get("Projectile", somePosition, someRotation);

Returning A Pooled Object

To return an item to the pool, simply deactivate its gameobject. This will make it available for other scripts to use.
The UVC kits include a Deactivate After Lifetime component, which can be used on projectiles, hit effects and other effects to disable them after a specified time and return them to the pool.

Setting Up Object Pools

When you get an object for the first time from the pool manager, it creates an object pool. When this happens, it may affect performance, because several items are created for the pool.
To avoid this, you can manually create your own object pools in a scene with a specified number of starting units. The pool manager will automatically find and use them, avoiding that first-time glitch.
To create an object pool:
  1. 1.
    Create a new gameobject in the scene and add an Object Pool component to it.
  2. 2.
    Drag a prefab into the 'Prefab' property in the inspector.
  3. 3.
    Set the number of default units in the inspector. This is how many will be created at the start.
This pool will be used by the Pool Manager when the object is needed.