2D Game UI: Ammo Count

Manny Cabacungan
2 min readJun 26, 2023

--

Objectives:

  • Limit the lasers fired by the player to only 15 shots
  • When the player is out of ammo, provide feedback through on-screen elements or sound effects. (ie: beep or ammo count displayed on screen)

I decided to represent the ammo count through the UI, just below the Score count. Let’s begin in the Hierarchy pane and select the Canvas game object.

  • Add a text UI game object.
  • Change the name of the game object to “Ammo_Text” , anchor it to the upper right and position it underneath the score text.
  • Give it the text “AMMO: ” and change the text color to white.
  • Open the UIManager.cs script.
  • Add a Text variable for the ammo text UI text you made in the Hierarchy and a string variable for the text ammo prefix.
[SerializeField] private TMP_Text _ammoText;
private string _ammoTextPrefix = "AMMO: ";
  • Back in the Hierarchy, select the Canvas game object.
  • Drag the Ammo_Text UI object to the “Ammo Text” variable in the Inspector for the Canvas game object.
  • Back in the the UIManager.cs script, make a new method for updating the ammo text to show the current number of ammunition the player has.
public void UpdateAmmo(int _playerAmmo)
{
_ammoText.text = _ammoTextPrefix + _playerAmmo.ToString();
}
  • Open the Player.cs script.
  • Add a new variable to track the ammo starting with the 15 maximum ammunition.
[SerializeField] private int _ammoCount = 15;
  • In the Start() method, add an “else” to the _UIManager’s null check and then call the UpdateAmmo() method to initialize the ammo’s display count.
if (_UIManager == null)
{
Debug.LogError("Player::Start:No _UIManager");
}
else
{
_UIManager.UpdateAmmo(_ammoCount);
}
  • In the FireLaser() method, after the assignment of the variable _canFire, wrap the conditional statements for the variable _isTripleShotActive and playing the sound _sfxAudioSource with another conditional if statement for the _ammoCount variable if it’s greater than 0.
  • Before the statement for playing _sfxAudioSource, decrease _ammoCount by 1 and call the UpdateAmmo() method from the UIManager.cs script.
void Firelaser()
{
_canFire = Time.time + _firerate;

if (_ammoCount > 0)
{
Vector3 _laserPosition = transform.position + _laserOffset;

if (_tripleShotActive)
{
Instantiate(_tripleShotlaserPrefab, transform.position, Quaternion.identity);
}
else
{
Instantiate(_laserPrefab, _laserPosition, Quaternion.identity);
}

_ammoCount--;
_UIManager.UpdateAmmo(_ammoCount);

_sfxAudioSource.clip = _laserShotAudioClip;
_sfxAudioSource.Play();
}
}

When you test it, the player’s ammunition count will decrease with every laser fire and stop once the ammo count is zero.

--

--