Project 1: Space Shooter

How to limit amount of ammo in a game

And showing it visually to the player

Eero Saarinen

--

Showing that the UI element for ammo count works after every shot, and that the player cannot shoot after depleting all the ammo.
The updated to the ammo count UI element work and the player cannot shoot after the ammo count is zero.

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.

The code for updating the ammo count UI element.
How to update the UI element for the 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.

The updated code to check if the player can shoot in the player script’s Update method.
Checking if there is any ammo left before the laser being fired.

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.

The code for reducing the ammo count and the UI element update after reduction.
The ammo count reduction and the UI element update with new ammo count.

--

--