Adding An Ammo Count in Unity
In this article, I am going to talk about how to add a simple ammo count to your game. This will include adding the ammo counter to the HUD and when ammo reaches 0, the text will change colors to red to alert the player. Also, when the ammo count hits 0, the player can no longer shoot. Let’s dive in!
In the Player script we need add some variables. We are going to create two public ints and one is going to be the Max Ammo and the other is the Current Ammo. The next variable will be a boolean and will keep track of whether the Player has ammo or not. This will be set to true at the very start.
In the on Start, we just want to make sure the current ammo is the same as the max ammo.
Now, in the Firing method we will take 1 away from the current ammo each time FireLaser is used and we check to see if the current ammo is less than or equal to 0. If that is true, we will switch our variable, hasAmmo, to false.
In the update, we are calling the Firing method when the space key is press. What we add was another check using If hasAmmo true and if that is true, then FireLaser will be called.
At this point, when the player is out of ammo they can no longer shoot. I will cover adding in an Ammo pickup in the next post. Next, we need to add the ammo count to the HUD.
In the Canvas, we will add a new TEXT UI element and rename it Ammo Count Text. We position to where we want on the screen and change the Text to “Ammo:”.
Let’s hop into the UI Manager script and add a Text variable with Serialize Field attribute.
Since it is Serialized, we can assign the Ammo Count text to the UI script which is attached to the Canvas.
We will need to access the Current Ammo variable from the Player script, so let create a Player type variable.
In the Start, we need to find the “Player” GameObject, get the Player component and set it to the player variable.
Still in the UI Manager script, using the Update, we can access the Ammo Text using script by using our Text variable _ammoCountText.text and set it to the text string “Ammo:” plus the Current Ammo. We access this using _player. and since it is a public variable we can use it. This will update the Text in the UI by adding the current ammo number. The last step we want to check to see if the player is out of ammo and if they are we can change the Text color to another like Red.