if you’re just starting out, you may never have heard of object pooling. But, guaranteed if you’re going to have a lot of objects on the screen, this is key. So, let’s share the secret sauce of object pooling.
Object Pooling Explained
First, let’s explain the scenario where it’s useful. You’re creating a shoot em’ up game and you need to have the player and enemies fire projectiles at each other. You developer your shooting mechanics and fire elements both for the player and enemies. However, these objects don’t just disappear They have to be handled once they finish their job.
You could handle them with deletions; recreating and deleting objects constantly. To be honest, that gets expensive very fast. The other option is to reuse the object, and that’s where object pooling comes in.
The idea is that we might have a list of projectiles, and once they handle their task, they go back in the list for use later. Essentially, they are pre-instantiated for use. So, the projectile visibility is gone once it hits a target or heads off the screen. But, we hold on to it, keeping our processing power low. Here’s code demonstrating that.
As you can see, we fire projectiles like normal with the key difference of using a list, rather than creating new objects every time. The conditions for disappearing(Being available again) allow us to create smooth shooting action with a minimal performance impact. The poolPlayerProjectiles method handles the condition for disabling it from view and telling us it’s available to use again. The fireProjectiles function handles figuring out which projectile is available in our list to use based off the visible property that we manage in poolPlayerProjectiles. As a result, we barely have any performance hit and we can keep shooting objects within our ammo limit. Told you, this trick could definitely help you out.
With that said, stay tuned for our next post, and if you want to continue to stay updated, follow the blog!
If you would like to see the example online you can find it here: Object Pooling Example.