The pattern of which I speak today is part of the tools against the waste of resources. I have already written some articles about it advising not to use too often the keyword “new” especially in methods that are called continuously.
The object pooling helps us to lighten the workload by removing two very expensive operations in Unity. I speak of Instantiate and Destroy. That is the insertion and removal of a new game object in a game scene.
The optimization principle is the same, let’s start by building the resources that we will use later.
We begin by seeing what we need:
Let’s imagine the most classic of simulations, a series of bullets being fired. Then we will have to create a prefab of the bullets and the manager that will manage this sequence of operations.
Let’s start with the Pool Manager, to avoid problems and to be able to call it later we use the Singleton design pattern, we define a game object that we will make visible by the Inspector for the prefab we want to add and we build a list of game objects.
we are going to write the method that will be called in Start. In this method, we are going to install and populate the list of game objects with the projectiles that we will use in the future.
The next method will be called by the other components of the game, in my case, it could be the player pressing a button for the shoot command.
In this method, we go through the list of game objects and look for one that is currently not active. If it is found, it moves it instantly to where it is needed. If it doesn’t find an available game object it means that we are in the worst case and we have to generate a new bullet at runtime and add it to the list so that it is not wasted but can be used later.
Finally, we move to the script of the projectile where we have defined its behavior, where instead of destroying it we will simply deactivate it after it has done its job.