Unity3D – Object Pooling

What is a pool?
In computer science, a pool (piscina) is a set of initialised resources that are kept ready to use, rather than allocated and destroyed on demand.
A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished with an object (or resource), it returns it to the pool rather than destroying it.

What is object pooling?
In games you need to manage a lot gameobjects at one time (bullets, enemies etc…), and istantiate and destroy every object can slow down your game performance.
To improve performance and save CPU time the best way is create a pool of gameobjects and request gameobjects from the pool.

For example you can have an gameObject off screen named “enemies” which holds all the enemies, and a master script to manage it:

enemies (Empty Game Object) -> master script ‘Enemy.js’
|
|—-enemy
|
|—-enemy
|
|—-enemy

Another example is reuse bullets:

Slower performance:
1. Awake(), do nothing
2. Update()
a- Instantiate bullet in its start position
b- Move along the way
c- Move bullet in its final position
d- Destroy bullet

Object Pooling. best performance:
1. Awake(), create a pool off screen
2. Update ()
a- Get gameobject bullet from the pool
b- SetActive -> true, Move bullet in its start position
c- Move along the way
d- Move bullet in its final position
e- SetActive -> false
f- Reuse from point b- and so on…

In terms of performance for real scenarios, if you use only 10-50 gameobjects at one time the benefits of object pooling are irrelevant.

In Unity3D you will need object pooling when you have thousands of gameObjects at one time or if you develop for slower mobile devices.

References:

http://answers.unity3d.com/questions/321762/how-to-assign-variable-to-a-prefabs-child.html

http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling