Object Pooling
Object Pooling is a way to re-use objects without having to re-initialize them. Instead of removing & instantiating an object multiple times, it simply enabled/disabled them, improving performance.
Last updated
Object Pooling is a way to re-use objects without having to re-initialize them. Instead of removing & instantiating an object multiple times, it simply enabled/disabled them, improving performance.
Last updated
To get started using Object Pooling we need a place to store ALL the objects.
Create a Resources
folder anywhere in the project structure. Here we can create a new Pool
object. Right-click inside the folder and select Create/Essentials/Pooling/Pool
.
If you are creating your own Pool
like above, you must remove the Pool
in the Pooling/Demo/Resources/Pool
or you can just use the same one as the demo.
Now we have created a Pool
object that stores all our poolable objects.
There must always be exactly one Pool
object in the project.
To actually pool an object we need to extend the APoolable
class. We can replace any MonoBehaviour
with APoolable
to make an object poolable.
Will become:
When a poolable object contains multiple MonoBehaviour
components or has children that contains MonoBehaviour
, you need the other (everything except the poolable class) to inherit the IPoolableFamily
interface.
For example; if we have another MonoBehaviour
next to the original poolable script:
When using a poolable object, we must replace Unity's default Awake()
and Start()
methods with OnAwake()
and OnStart()
, respectively.
Now that we have converted our object to be poolable we should add it to the Pool
. Select the Pool
object we created earlier and add a new entry under the Objects
tab. Here we can define which object we want to pool and how many of those objects should spawn initially. Drag your poolable prefab onto the Object To Pool
and change the Amount To Pool
to 10
.
If we start our game it should.. not work? We get a warning telling us that the Pool has not been initialized
. This is simply because we need to call Pool.Init()
whenever we want to start the pooling process. This should usually be done at the start of the game.
We could simply call Pool.Init()
in a Awake()
method:
But, currently it initializes only when this scene is called. Another, better way, is to initialize it using:
Now, if we run our game again, we can see that the pooling system has spawned a couple of instances of our poolable object in the DontDestroyOnLoad
scene.
To instantiate our poolable object we replace Unity's default Instantiate()
method with Pool.Acquire()
:
To later destroy our poolable object we replace Unity's default Destroy(poolable)
method with poolable.Dispose()
: