Adding an Ammo Count UI Display Feature in Unity!

Objective: To give our player one final visual cue for their ammunition, a maximum and current ammo text display.

Previously we have provided the player with a visual cue in the form of a flashing ‘OUT OF AMMO’ warning and also an audio cue that plays also when the ammo is empty. Let’s now give the player one last visual cue to help them battle it out with the space invaders!

Within our ‘UIManager’ script let’s add the following code:

We need to create a new handle to our _ammoDisplay Text variable which we are going to drag and drop into the Inspector on the Canvas game object which holds our ‘UIManager’ script:

Then, we need to create a new method UpdateAmmoDisplay() which is going to be called from the ‘Player’ script and takes 2 parameters which is going to be our currentAmmo and maxAmmo.

We are now going to call this method from 2 places in the ‘Player’ script as we want this UI display to be updated as quickly as possible. The first is within the Update() method after the player fires a laser (reduce ammo count) and the second is when the player picks up the ammo refill powerup (increase ammo count):

Let’s now create a new Image which is going to display our laser sprite as an ammo icon. Right click on Canvas → UI → Image and rename to Ammo_Image.

Now let’s make a few changes the to ‘Rect Transform’ and also don’t forget to anchor this to the far left. We also need to drag in the laser sprite image into the ‘Source Image’ box.

Moving onto the Text UI portion, let’s right click on Canvas → UI → Text and rename to Ammo_Display. Again let’s make some adjustment to the ‘Rect Transform’:

And we also need to make some adjustments to the ‘Text’ component:

The 15/15 will show next to the laser icon at the start of the game to indicate full ammo. We also need to change the text colour to white so we can see it!

Lastly, the method that we initially created UpdateAmmoDisplay(), is going to receive 2 parameters from the ‘Player’ script, constantly updating the live ammo count:

Aspiring Unity Game Developer with a passion for bringing code to life!