Adding an Ammo Counter

Daniel Jennings
3 min readAug 8, 2021

--

Adding limits on how much the Player can shoot

Task:

We want to add a limit to how many times the Player can shoot at enemies.

Plan:

We will need to implement a counter variable to keep track of the current ammo left. On fire of laser we will need to decrement the laser count. When the Player is out of Ammo come up with a out of ammo feedback system.

Process:

Just like last time, let’s start by adding a counter… Scratch that…

If you didn’t catch the update from the Shield upgrade, I moved all of the shield logic to it’s own class.

So let’s try this again.

Like last time, let’s start by creating a class to handle the ammo count and related logic. We will then grant access to the ammo class to the Player script.

Sweet!! That was pretty simple. Now how to we use this in Player??

We have the key detection and can fire cool down in Update. Adjusting this logic to add another variable in the mix seems overly complex. Let’s leave this alone and look into FireLaser.

Wrap the fire logic with a check for the Player having ammo. If the Player does not have ammo then call PlayerOutOfAmmo which will handle our notification to the Player. For now we will add it to the Player, but we may want to add this to the UIManager for cleaner code.

PlayerOutOfAmmo will start with a beep notification to the Player. This will let the Player know something is wrong but does not seem to be the best (or complete) method of sharing info with the Player.

Let’s jump over to the UIManager and see what we can do to help inform the Player.

Opening up our canvas, let’s duplicate our Score game object and rename its contents to ammo.

Then rearrange it so it is below the score text.

To add a little more pop to the UI we will have 3 different colors for the Ammo Count. White is normal and greater than 5 shots remaining. Magenta is for between 5 and 1 shots remaining. Red is for no shots remaining.

It is also good to label your indices if possible. We will use an enum to label our index values with status color.

On UpdateAmmo, update the score text and the color based on the value of the ammoCount variable.

The screen capture of the game play was too powerful so we have screen shots instead. Here is warning at 5 shots remaining.

And alert on no ammo remaining.

--

--