Unity 2021 Object Pooling — Part II
The awesome ease of its use…and more pitfalls
In the previous article, I showed one pitfall waiting for the unwary who start using Unity’s object pool. Here is another, though to be fair, it isn’t actually a pitfall of Unity’s Object pooling but any object pooling.
In my space shooter game, I have enemy spaceships. In continuation of the previous article, it made sense to have enemy spaceships also be pooled. I was creating them every level and destroying them all the time, after all.
So I created an
enemyPool in the same way as the
playerLaserPool from the last article, and returned them to the pool when they were destroyed. No problems here! Right…?
In level 1 they moved great. In Level 2, they decided to do the jitterbug.
It didn’t take me long to figure it out. The spaceships were told to move at a certain rate according to the level. I did this using
Before I just destroyed them when done, so they didn’t move forever. Now, however, they were. And in the new level, I simply added an additional
InvokeRepeating, with another rate.
Which brings me to the second pitfall:
You must reset the objects before returning them to the pool.
In addition to the InvokeRepeating, there was yet another problem. As you see above, I have a movement integer that defines the movement direction. As each spaceship is destroyed at a different movement, this also needed to be reset.
So the ResetEnemy() function became:
And I call it before releasing the enemy spaceships back to the pool. And now they move as they did before.
To conclude, no matter what method of pooling you’re using, you must reset the state of the object: cancel any InvokeRepeating calls, and reset any variables to their original state.