The object pooling design pattern is one of the most used patterns in the game industry. It’s the design pattern that you must know if you want to make games, as you’ll find the need to use it everywhere. Also, once you learn using it, it’ll be incredibly helpful.
You can download the project with the object pooling example here.
What is the object pooling?
Object pooling is a design pattern used to recycle objects in your games. What do I mean with recycling? Let’s take the classic bullet example;
You have a simple situation in your game where you are shooting a cannon ball. Each time you press the shoot button, a new cannon ball will be created. If during your match you press the shoot button a thousand times, then thousands of cannon balls will be created.
If you think about it, this is not efficient at all as each time you shoot, you have to allocate a new object into the memory that will be destroyed later. Wouldn’t it be better if we have a pool of cannon balls to use each time we shoot?
Object pooling in action
This is how it works:
- Create a pool of cannon balls somewhere in your game.
- Each time we shoot, we will take one cannon ball from the pool.
- We’ll shoot the cannon ball that we’ve just taken.
- When the cannon ball hits the target, instead of destroying it, we’ll place it back into the object pool area.
Why use object pooling?
The purpose of object pooling is all about efficiency. Without object pooling, you have to create an instance of an object each time you want to use it. This is happening at runtime, which can lead to inefficient memory management especially in languages with garbage collector such as C#.
If you use object pooling instead of creating and loading new objects at runtime, we’ll move all the effort at loading time. In other words, we’ll create and load all the objects that we want to use as soon as the game starts. After that, we can always reuse all the objects that we’ve loaded without having to carry too much of the memory management and efficiency since we don’t have to create new ones.
Object pooling Unity C# Example
Step One: Create a pool of objects:
In this first step, we’ll create inside the unity editor a set of objects that will be ready for recycling:
As you can see, we’ve created a GameObejct called Pool which contains a set of objects to recycle. We move this object to the upper right side of the screen in order to show you at runtime how the object pool is working.
Step Two: Object pooling logic:
Let’s create a script that we’ll use to pool the objects For this example, the script will do something really easy:
- We’ll take a random object from the pool.
- We’ll move that object into the center of the screen,
- After 1 second we’ll set the object back into the pool area.
This is exactly like the example that we did before with the cannon balls.
using UnityEngine; using System.Collections.Generic; using System.Collections; public class ObjectPoolingManager : MonoBehaviour { #region FIELDS public List objectToRecycle = new List(); // Used to keep traking od the objects that we can use in the game public Transform originlPoolPosition; // used to reset the position of the object that we've pulled private GameObject _selectedObject; #endregion #region MONOBHEAVIOR void Start() { InvokeRepeating("Shot", 1.0f, 2f); //Shot an object every 2 seconds } private void Shot() { SetObjectFromPools(); _selectedObject.transform.position = Vector3.zero; // Move the object to the center StartCoroutine(ResetTheObject()); } //Get an object from the pool and remove it from the pool once is selected private void SetObjectFromPools() { _selectedObject = this.objectToRecycle[this.objectToRecycle.Count - 1]; this.objectToRecycle.Remove(this.selectedObject); } //Readd the object to the pool and reset his position private IEnumerator ResetTheObject() { yield return new WaitForSeconds(1); _selectedObject.transform.position = originlPoolPosition.position; this.objectToRecycle.Add(this.selectedObject); } #endregion }
Attach the above script into a game object in the scene and drag the object as shown in the following screen:
This script does exactly what we’ve listed before.
Conclusion:
This was a brief introduction into the world of object pooling. With this basic concept, you’ll be able to create complex object pooling logic and develop efficient games.
Dude, why did you use “this” to refer to the scripts inside the same class? That’s the first time I saw someone doing it.
I used this to refer to internal fields since the underscore is not suggested to be used: https://msdn.microsoft.com/en-us/library/ms229045.aspx
Do you have any performance metrics to justify the use of an object pool? I would think object pooling is beneficial only of each object is heavyweight, or is expensive to create. Nowadays garbage collection should be efficient enough to take care of such a scenario no?
Hello, Here you can have more information about performance and other interesting stuff.
Hi, you shouldn’t create the pool objects by hand, create them run time. Further more your code getting the object from the pool will break when you need more objects than you have in your pool.
I suggest that you prefill you pool objects in a Start or Awake routine with a certain amount of objects. Then change your SetObjectsfromPool routine that it checks if there is an object available, when not create another object on the fly.
Further more I think it’s a bad habit setting a variable instead of returning the right object so that you can call the routine from other classes, too.
Anyway.. keep up the work!