Pooling - SebastianKErben/SKE.Unity3D GitHub Wiki
The Pooling namespace consists of only one class derived from Unity3D's MonoBehaviour: PoolObject. The idea is that every prefab object you create can be turned into an object that will self manage all its instances. Converting your prefabs base MonoBehaviour into a pool object is done by changing
public class MyCoolObject : MonoBehaviour {
to
public class MyCoolObject : PoolObject<MyCoolObject> {
In the Inspector view of Unity3D, reference the prefab object in the public field member
prefabReference
and make sure to implement the clearing process where all values will be set to their default values in the MonoBehaviour OnEnable method.
Once your prefab is finished, you can spawn instances of the prefab by calling the
GetInstance()
method of the PoolObject class instead of using
Instantiate(prefab)
like you would normally do and use the
Return()
method of the PoolObject class instead of using
Destroy(instance)
This way the pool will automatically grow as you Return objects to it and existing objects are taken from the pool instead of new instances being created at runtime all the time. Of course the best useage of object pooling is through prefilling a pool with objects that are ready to use. For this, the PoolObject class provides the
Ready(int amount)
method which your spawner can call for example on awake to fill the pool up with a certain amount of instances ready to be used. Because the PoolObject class will automatically provide additional instances if needed, it can grow substantially in high demand scenarios. If you know those scenarios and want to reduce memory usage after those scenarios are over, use the
Clear(int amount)
method of the PoolObject class to reduce the size of the pool by a certain amount by destroying instances. Take a look at Examples/Pooling for a better understanding how to use the PoolObject class.