Object Pooling in Unity (Design Pattern)

Marcus Ansley
3 min readJul 1, 2021

--

Theory

Object pooling offers a way of reducing the burden placed on the CPU when rapidly creating and destroying GameObjects. One of the examples typically used for this is in a something like a top-down shooter, in which the player might be firing a large number of bullets in a short space of time. Rapidly instantiating and destroying each of these bullets can be incredibly expensive, so object pooling seeks to address this by pre-populating the scene with the bullets that can be used, setting them to inactive (in Unity’s case, via the GameObject.SetActive method), and then having them repositioned and activated for repeated use. Essentially, we’re recycling a fairly finite number of objects (in this case bullets) while maintaining the illusion of creating new objects each time.

Implementation

The way I’ve been taught to implement this is through the use of a dedicated ‘PoolManager’ class (or equivalent), which will create and manage a List of GameObjects which can then be accessed via, in this case, a Player class. I’ve opted for using a Singleton in addition to this, just so my Player class can more easily draw from this manager. I’ll include my full code below:

At the start of the game, I’m generating a list of bullets by Instantiating them, setting them to inactive, changing their parent (purely for organisation), and then adding them to a list of GameObjects. I then have this public RequestBullet method, which will return the first inactive bullet in the bullets list that it can find. If it can’t find one (i.e. they’re all active/still on screen), then I’ll return a new bullet (which will be generated and added to the list, increasing its size permanently). If 10 bullets isn’t sufficient for whatever reason (for instance the player can fire them very quickly), then this pool has the ability to adjust accordingly.

The Player class would call this RequestBullet method, then position the GameObject as it would if it were instantiating it.

The second key part of this object pooling system is that we need to hide rather than destroy these GameObjects, and we need to use the OnEnable method rather than the Start method. Using the OnEnable method means that every time we enable this GameObject it can essentially call the same startup code as it’d been newly-instantiated (in this case, something to the effect of ‘move forwards until off-screen or until a collision’).

(This code isn’t complete/ready for these to be used as bullets)

Because of how we set up the PoolManager class, as soon as this bullet’s set to inactive it can be re-retrieved from the list using the RequestBullet method. And with that, we have an object pooling-based bullet system 😉

--

--

Marcus Ansley
Marcus Ansley

Written by Marcus Ansley

Game Developer | Game Design and Literature Graduate

No responses yet