Framework: Object Pooling for Optimization.

Suleiman Abdullah
4 min readMay 7, 2023

--

In the first step, I will create a new script called PoolManager and turn this class into a singleton.

Create three variables a list of game objects, int, and game Objects called _objectTobePooled,_aiObjects, and _amountofAI.

Now create a return List method called GenerateAI.

To generate an AI we need to create a handle of the game object and instantiate a pooled object. Then we add this object to the list, since we need to create many AI I will use for loop to iterate with amountofAI we assign in the inspector, last we will return the list.

When we create _aiobjects we need to deactivate our object and also I will put this list as a child of other containers to make my hierarchy looks clearer.

Create a Start method and assign our list to the GenerateAI method, which will return the list of AI created in the method.

To request ai we need to create a public method called requestPooledAI.

Now we need to loop through the list and then check if we have in-active ai, we activate it a return it to the scene.

But if all AI is not available we need to create one and add it to the list, then set it transform as the parent transform and return to the scene.

Note: In your game, you may not want to create more enemies.

Before going to the spawn manager I will delete the call of spawning ai from GameManager. Then go to the Spawn Manager, create GameObject in SpawnAIRoutine then assign the RequestedPooledAI to that handle of GameObject then I will use that variable to access the model/child(AI which has script) and position the model to the initial position when I instantiate the AI.

Note: If you follow this article from the previous article,I instantiate an AI in SpawnAIRoutine, so now I delete the old code and replace it with this code.

I will call the Spawn Enemy in the update method in the same script SpawnManager.

I want to be able to recycle the pool, so first I will go to the AI script and then disable the ai when he reaches the destination to give the sense AI breaches the door. But due to my AI logic, I have to deactivate the parent object and reset the position of the AI object, also I will want to reset the wayPoint index and bool variable.

Note: you can deactivate the AI when you shoot him to be able to recycle.

This is how I Implement an object Pool in my game, It was a little bit challenging to understand the parent's position with the child but I learn a lot, I hope you learn a lot too.

Note: As you see only seven objects are recycled, this saves the performance of the game.

See you in the next article.

--

--

Suleiman Abdullah

Self taught Unity Developer, who is passion about making games ,and he loves Math For Game Development