Galaxy Shooter: UI Ammo Count and Slider

In this article I will show how I setup a start count of 15 and max count of 50 for my Player’s ammo count and display it in the UI along with a slider for visualization. I also setup a warning sound when the ammo reaches 0 and turn the text and slider/meter red.

I first duplicated my Score text and changed the name, text, font size and anchor to bottom right. I then positioned it where I wanted it.

Next I created a Slider, named it Ammo_Slider. It wont be interactable so I unchecked that box and deleted the extra child objects I wont be needing, leaving just the Fill Area and its child object Fill.

Next I positioned it near the ammo count text and changed some values as you can see in the pic below.

Now that it’s all positioned how I want it I can move onto the Player, UIManager and AudioManager classes to get it all hooked up.

First in my UIManager class I added variables for each new UI part that I need to change and also one for the warning audioclip that I will pass to my AudioManager.

I created a new method named

UpdateAmmoUI(int ammoCount, int maxAmmoCount)

This is the method that changes everything in the UI and also lets the AudioManager know to play the warning sound when ammo runs out.

This method is called through an Action event in the Player class named OnPlayerShoot that the UIManager is subscribed to, invoked each time the player fires. The AudioManager is subscribed to one in the UIManager named OnPlayUISound.

Now I’ll show how I have it setup in my Player class…

I added an Action named OnPlayerShoot that will let the UIManager know when the player shoots with the FireLaser() method. This takes 2 ints so I can pass the _ammoCount and _maxAmmoCount to the UIManager.

public static event Action<int,int> OnPlayerShoot;

In my FireLaser() method I simply added an if statement so that it can only fire if _ammoCount is more than 0 and then after decrementing the _ammoCount I invoke and pass the info through the OnPlayerShoot event to the subscribed UIManager which uses it’s UpdateAmmoUI() method as seen above.

For the warning sound to be played by the AudioManager when the ammo runs out I added an empty gameobject as a child to the Audio_Manager in the hierarchy and named it UI. I attached an audio source component to it and unchecked loop.

I added another AudioSource variable for this in my AudioManager and dropped it into the filed in the inspector.

I also created a method named PlayUISound that takes an AudioClip parameter.

This PlayUISound method is called whenever the OnPlayUISound event that it is subscribed to in the UIManager is invoked.

For the warning sound when the ammo runs out I invoke it if the ammoCount equals 0 as seen below.

Unity Developer/C# Programmer for VR, 2d,3d Games and other Immersive Interactive Experiences