Project 1: Space Shooter
How to limit amount of ammo in a game
And showing it visually to the player
Limiting the ammo couldn’t be simpler in a game made with Unity. Once the UI text element is in place, the UIManager script needs to be updated with a new public method that updates the text with the new ammo count.
This will be in turn called in the Player script which handles the firing. The first thing is to add a new _ammoCount variable, which holds the amount of ammo the player currently has. I also added a _maxAmmo variable in case I want to implement an upgrade for the max ammo count, also so that the ammo count can’t go higher than that.
Then in the Update method the if-statement that allows the player to either shoot or not needs to check if the player has any ammo left. If the player has shot all their ammo, this will prevent the FireLaser method being called, thus making it impossible for the player to shoot.
After all that, in the FireLaser method the _ammoCount has to be reduced by one for each shot made. And the very last thing is to call the UIManager to update the ammo count, so that the player knows how many shots they have left.