Object Pooling Design Pattern in Unity

Object pooling is a design pattern that will allow you to reduce the amount of garbage collection you have when working with instantiating multiple objects. One of the easiest examples of when this could be used is for bullets in a shooter game.
To set this up you will create an empty game object that will be the pool manager for your game. You will also create the pool manager script and attach it to the pool manager game object. You will also want to make a game object that will be used to hold the bullets to keep the hierarchy clean.


Make the pool manager script a singleton to allow all scripts easy access to it.

Create a reference to a prefab. Create a list to hold the prefabs and a variable to tell the game how many prefabs to instantiate. You can also make a container prefab for the bullet container.

Create a method that will return as a list. This method will take an integer parameter, loop through, and create a prefab based on the integer given. Once a bullet is instantiated it will be parented to the container and disabled.

Set your list equal to the generate bullet method.

You can create a public method to find an inactive bullet in the list and use that as the bullet you are firing. If there is not an inactive bullet it will create one. This allows the game to use existing bullet prefabs instead of creating new ones in most cases.

I created a simple player script to shoot and attached it to the main camera for this example. When the player left-clicks the request bullet method is called and the position of the bullet is set to (0, 0, 0).

The last part of this is to set the bullets inactive after a set amount of time. This is done using OnEnble and invoking a method that will set the object inactive after a specific time.

In unity make sure to set all of your references and the number of initial bullets you want.

This will allow your game to create a set amount of prefabs and recycle them instead of instantiating multiple prefabs. This will reduce the amount of garbage collection in your game and make it more efficient.

