Using Unity’s Built-In Pooling System in Unity 2021 URP

In this article, we’ll convert the cannon project from a few articles ago to use Untiy’s built-in pooling system that is available in Unity 2021 or higher.

Unity’s documentation linked above doesn’t quite give a clear idea on this, but there are many articles out there by others.

Still, I found that most of the articles wanted to modularize the pattern into a spawner class and a class to pool approach.

That is a great approach, but it tends to obfuscate what is going on for someone just learning about it for the first time.

This article will give a more straight-forward implementation within a single class/script which can be used to build out those more complex approaches in the future while assuring a better understanding.

It all starts with the “using UnityEngine.Pool” statement.

We then declare a class variable to hold our pool using “IObjectPool<GameObject>” as the type.

In the Start() method, we instantiate our pool.

If we hover over this area, we get a nice description of the various things we are doing here.

We can get the same information from Unity’s website as well.

Essentially, there are four, often, in-line functions.
In my case, for clarity’s sake they are replaced by method calls.

Note that you do not end these with the customary “()”.

These include “createFunc”, “actionOnGet”, “actionOnRelease”, and “actionOnDestroy”.

These are followed by a 3 simple variables, the last 2 being the most important as they define starting and maximum capacity of the pool.

As we continue down the revised CannonControl script, we can see the advantage of not using in-line functions.

It is much easier and clearer to do multiple actions in a full method.

We can see that the poolActionOnGet() and poolActionOnRelease() methods are both key to properly resetting the pooled game objects as they leave and re-enter the pool.

Note that the pool passes around the game objects encapsulated in the base class of “Object” rather than directly as Game Objects.

I’m not sure if this is necessary and may look into directly passing around Game Objects in the future.

The remainder of the script operates the cannon’s rotation and firing mechanisms.

In the FIreCannonBall() method we can see an example of pulling a pooled Game Object.

When ready to return this same Game Object back to the pool, we “Release” it as shown above.

That’s it for this article!
I hope you found this helpful, I have a feeling I’ll be referencing this article myself many times in the future!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store