Cleaning the Object Pool
While working on my current project I came across an issue I wanted to solve involving Object Pooling. Now, I’m not sure if it would’ve affected my game much in regards to performance, but it was something I wanted to solve anyway. So here is my solution…
For a little backstory:
I am using object pooling in my current project for the player bullets, enemies, and power ups. The problem was that every time my player changed weapons, the Pool Manager would instantiate more bullets, adding to the existing bullets in the hierarchy. So, depending on how many times the player weapon is upgraded and downgraded, the hierarchy could have a ton of bullets, with only the most recently instantiated getting used.
My Solution:
After doing a bit of research on how to clean up the objects in the hierarchy and only finding ways to set them inactive, not destroy them, I decided on a solution. First, I created a new C# script called ClearChildren. Then, I attached it to the game object that holds the instantiated bullets in my hierarchy(for me it’s “BulletContainer”).
Next, I created a Method called ClearChildObjects. Within that method is an if statement that determines if the object has children. If true, a for loop iterates through each one and destroys it.
Over in the Pool Manager class, I created an Action called clearChildren. This Action is called in the method that gets the current weapon from the Player to determine which bullet to instantiate.
ClearChildOjects over in ClearChildren is subscribed to that Action.
The final result is all the child objects being destroyed every time the Player changes weapons. Exactly what I wanted. The script can be attached to any object that needs its children cleared. You could also pass in the amount of children to clear, or use more specific parameters.