What’s the point of using the Object Pooling?
Every time we instantiate and destroy in Unity, our action is inefficient and can slow our projects down because we are allocating memory and causing a CPU overhead.
When we have to use a large quantity of objects of the same type for a short period of time, we can use the Object Pool. Using the Object Pool, in fact, we can lighten the load recycling the object we use.
This way, we will have a significant performance boost when we have, e.g. manage the bullets of a gun in a shooter, or to create a path in a scrolling game.
Implementation (Simple):
All we have to do is add the SimpleObjectPool component to a GameObject in Scene and give it the Prefab of the GameObject to pool.
When we need it, we can call the Get() method that returns us the first Object available. If there aren’t, it will instantiate one and return it to us. When we have finished using an Object, we can recycle the object itself through the Recycle() method. This way, the Object will be ready to be reused.
Implementation (Advances, using Generics):
In this case, thanks to the use of Generics, we can Pool any type of Component and customize an event for the Recycle() and for the Get(). In this case the component to be Pool has to implement IPoolable interface, in order to use OnGet() and OnRecycle() events.
Example of IPoolable implementation:
This is an example of use in Unity:
All we have to do is call methods Get() and Recycle() on the Pool and, automatically, according to the implementation of IPoolable interface, will be also called OnGet() and OnRecycle() of the object taken from the Pool or recycled. If the latter does not implement IPoolable interface, it will raised an unhandled exception.
More information about Object Pooling are available here on the official Unity Learn section.
I hope this tip has been helpful and that you will use it while you’re working with Object Pooling in Unity 5!
Riccardo