Phase 1: Ammo Collectable
A few days ago I wrote an article where I implemented an ammo count system where the player has a limited amount of ammo they can shoot. Things turned out pretty well but we had one slight snag — we couldn’t regen the ammo if we ran out. Well, this is what today’s article is all about.
Today’s challenge is to implement an ammo collectable that will replenish our ammo when we collect a specific powerup.
Create a powerup that refills the ammo count allowing the player to fire again.
If you’ve been following my articles, you might remember we created a modular powerup to add new powerups to the system as we continue to work on our game and introduce new abilities and perks. Today we’ll be adding another power up to that system.
Creating the Logic
Before we cover the powerup in the game itself I decided to create the logic first. Reason being that I then know what powerup ID to assign to the powerup system and the powerup itself later on. Since this is the 4th powerup and our case starts at 0 then the ammo powerup will have an ID of 3.
In my ActivatePowerup function, I created a new case and this one has an ID of 3. To prevent an exception to be thrown we need to check if the ammo we have is less than the max amount we can hold. We do that with an if statement and checking if _ammoCount is less than 19. If that is in fact the case then we can set the ammo back to 19 and update the UI manager.
And just like that, we have created the ammo collectable powerup, but now we need to actually create the powerup.
Powerup Logic
Since we have the powerup created on our player, we need to tell the powerup system which powerup to trigger when the player interacts with it.
In our OnTriggerEnter2D function, we need to create a new case, this will correspond with the case in the player to avoid confusion when we need to debug our code.
All we need to tell the powerups system that if the powerup ID is 3, that the player’s ammo should be regenerated.
Creating the Powerup
Creating a new powerup is very simple. We can add an existing powerup from the prefabs folder and add it to the hierarchy, then unpack it so that we can make changes without affecting the original powerup.
Once the existing powerup was unpacked I renamed it to “AmmoPowerup” and assigned its value to 3 and replaced the image with another one that represents an ammo powerup. Once I was happy with the powerup I dragged it to the prefabs folder from which I could assign it to the SpawnManager.
Conclusion
In literally three easy steps we’ve added a new powerup that replenishes the ammo when the player collects the powerup. This is what I really love about modular systems in Unity. The bulk of the structure has been created already and now we can just build on top of that as we go along.