Updating the Ammo

Christian Carter
2 min readJul 21, 2021

This tutorial goes over updating ammo so that it has a max which is displayed on the screen. There isn’t much to this one since we did a lot when we created the ammo collectable which you can find here. The first step is to update the UIManager script. Update what you set the initial ammo text to in the Start function adding the max.

_ammoText.text = "Ammo: 15 / 30";

Then in the UpdateAmmo function add a variable for max ammo and add it to the text string.

public void UpdateAmmo(int currentAmmo, int maxAmmo)
{
_ammoText.text = "Ammo: " + currentAmmo + " / " + maxAmmo;
}

Next, go to the Player script create a variable for the max ammo.

private int _maxAmmo = 30;

Now update the first of two uses of the UpdateAmmo function to include the max ammo variable. The first is in the FireLaser function.

_uiManager.UpdateAmmo(_ammoCount, _maxAmmo);

The next spot to update is in the CollectAmmo function. Add an if statement to check that the ammo does not exceed the max ammo then update the UpdateAmmo function.

public void CollectAmmo()
{
_ammoCount += 10;
if (_ammoCount > _maxAmmo)
{
_ammoCount = _maxAmmo;
}
_uiManager.UpdateAmmo(_ammoCount, _maxAmmo);
}

With those simple updates now you have limited the players ammo to a max number.

Good Luck Adventurer!

-Chris

--

--