• Register
Post tutorial Report RSS Object Pooling in Unity 5

Object Pools (a.k.a. resource pools) are used to manage the object caching. Object Pooling is nothing but a design pattern where we have a pool of objects of the same type we can use and recycle. In this post, we will give you some tips to use Object Pooling when you work with Unity 5.

Posted by on - Intermediate Client Side Coding

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):

Object pooling 1

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):

Object pooling 2

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.

Object pooling 3

Example of IPoolable implementation:

Object pooling 4

This is an example of use in Unity:

Object pooling 5

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

Post a comment
Sign in or join with:

Only registered members can share their thoughts. So come on! Join the community today (totally free - or sign in with your social account on the right) and join in the conversation.

Tutorial
Tags
Coding, Uniti 5
Browse
Tutorials
Report
Report
Share
Related Groups
LEAF games & software
LEAF games & software Developer with 2 members
Unity Games
Unity Games Hobbies & Interests with 1,807 members