Limiting the Players Ammo
This tutorial will cover how to limit the player to 15 ammo, inculding a UI display to show how much ammo the player has left. To start add a text element to the Canvas. Place it in the lower left corner of the screen. Adjust the color and size of the text to match the rest of your UI. Set the initial text to Ammo: 15.
Next, go to your UIManager script to add the controls for the ammo text. Create a variable to reference the ammo text element. Assign the element to the variable in the Unity editor.
[SerializeField] private Text _ammoText;
In the Start function set the initial text of the element to Ammo: 15.
_ammoText.text = "Ammo: " + 15;
Create a function to update the ammo text based off of an ammo int passed to the functioin. This will be called by the player to update the ammo text.
public void UpdateAmmo(int currentAmmo)
{
_ammoText.text = "Ammo: " + currentAmmo;
}
Next, go to the Player script. Create a variable to keep track of the number of ammo the player has.
private int _ammoCount;
In the start function set the initial ammo count to 15.
_ammoCount = 15;
Now it is time to update your FireLaser function. Add an if statement to check if the ammoCount is greater than 0. If it is then let it fire as normal. If it is not it will not fire. Instead it will play a sound to show that it is unable to fire. An easy way to get this sound is to just play a portion of the laser audio source. This can be done by setting the time of the audio source to somewhere in the middle of it so you only get half the sound when you play it.
void FireLaser()
{
if (Input.GetKeyDown(KeyCode.Space) && Time.time > _canFire)
{
if (_ammoCount > 0)
{
_canFire = Time.time + _fireRate;
if (_isTripleShotActive)
{
Instantiate(_tripleShot, transform.position,
Quaternion.identity);
}
else
{
Instantiate(_laserPrefab,
transform.position + new Vector3(0, 1.05f, 0),
Quaternion.identity);
}
_ammoCount--;
_uiManager.UpdateAmmo(_ammoCount);
_audioSource.Play();
}
else
{
_audioSource.time = 0.3f;
_audioSource.Play();
}
}
}
Now the player is limited to 15 shots. Don’t worry, the next tutorial will cover adding an ammo container to restock that ammo.
Good Luck Adventurer!
-Chris