Unity/C# Challenge 25: Ammo Count

Alec Oney
3 min readAug 13, 2021

Challenge: Implement a basic ammo system into our Unity game.

Currently, our player is capable of firing as many times as you can click. We are going to implement an ammo system to limit this. Our ammo system is going to consist of two parts:

The code limiting shots to 15;

and the UI to show the player how many shots they have.

Right now, our code governing the player being able to shoot looks like this:

Where every time we fire, our fire rate gets reset (limiting the amount of shots/second), and then our laser gets fired (single or triple shot, depending on power up). Finally, the laser sound plays. To update our code, first we want to establish an integer for our ammo count:

And update our code to look like this:

where, when we hit the fire button, it will check to see if we have ammo. If we have ammo, it will fire, remove 1 ammo count, and play the fire sound. If we DON’T have ammo, it will tell us in the log that we are out of ammo. This allows us to go to the second part; updating the UI. First, we create an ammo text in our UI, set our ammo integer in the Player script to public (from private) and create handles in our U manager script:

Where our UI text we created will be linked to _ammoText. Then, we link _player to the Player script in the start method:

and create public void in our UI manager:

Where our ammo count will match the player’s ammo count and then display in our text (or show out of ammo). Finally, we need to put the UpdateAmmo method into the start function of our UI manager as well as the player’s fire function:

resulting in:

--

--