Feature: Ammo Supply and Ammo Pickup

In this article, we will add a limited amount of ammo for the Player that will be visualized on the screen and a collectible to refill that ammo.

Ammo Supply

Implementing a limited ammo supply is pretty simple. In the Player script, you need two variables: the maximum ammo capacity and the current ammo amount.

The Player should start with full ammo. So in Start, set the current ammo amount to equal the maximum ammo capacity.

In Update, when checking if the Player can fire, add another condition to check that the current ammo is greater than 0.

In the FireLaser method, after instantiating the Laser Prefab subtract one from the current ammo.

With the code added, now the Player can only fire 15 times before running out of ammo. Now to make it visible on the screen.

Ammo Count

To show the ammo amount, all that is needed is a Text GameObject.

In the UIManager script, add a Text variable that will be a reference to the Text GameObject.

Now add a public method with arguments for the ammo remaining and the maximum ammo to update the ammo text with the ammo remaining and the maximum ammo.

Back in the Player script, in Start after the Init call and setting current ammo, call the UpdateAmmo method on the UIManager and pass in the current ammo and the maximum ammo. That will set the ammo text to 15/15.

Now add a call to UpdateAmmo, passing the current ammo and maximum ammo after subtracting one from the current ammo in the FireLaser method.

Hook up the Ammo Text GameObject to the Ammo Text field on Canvas’s UIManager script.

In Play Mode, the text will be set to maximum ammo at the start and go down by one each time the Player fires.

Ammo Collectible

To create an ammo collectible, we need to create a public method in the Player script to change the current ammo to maximum ammo and then call the UpdateAmmo method passing in the changed current ammo and the maximum ammo to update the UI. The ChangeAmmo method is what the ammo collectible will call when collected.

In the PowerUp script, we need to add an Ammo element to the PowerUpType Enum for the ammo collectible.

Then we need to add the PowerUpType.Ammo case to the switch statement and have it call the ChangeAmmo method on the Player.

Now to create an Ammo Power Up to put the script on.

With that, the Ammo Power Up now restores the Player to full ammo.

Unity Developer, Software Engineer, Game Designer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store