Adding ammo limit and providing feedback by UI/Audio

Jaime
2 min readMay 26, 2021

The best things in life are not free, unfortunately. That being said, we will need to restrict the number of lasers that can be fired and provide feedback to the user through display and audio.

First, I’ve implemented the ammo left by text and can be updated by a delegate:

public class UIManager : MonoBehaviour
{
[SerializeField]
private Text _ammoText;
private void UpdateAmmo(int ammo)
{
_ammoText.text = "Ammo: " + ammo;
}
public void OnEnable()
{
Player.UpdateAmmoLeft += UpdateAmmo;
}
private void OnDisable()
{
Player.UpdateAmmoLeft -= UpdateAmmo;
}
}

On the Player, I’ve added the attributes to keep count of ammo and audio feedback and a delegate to be able to update score UI.

[SerializeField]
private AudioClip _laserEmpty;
private int _ammoLeft = 0;
[SerializeField]
private int _maxAmmo = 15;
public static Action<int> UpdateAmmoLeft;

Finally, I needed to update the FireLaser method to only be able to fire laser if there’s ammo left and deduct from available ammo. Calling the delegate UpdateAmmoLeft updates the ammo display. Finally, I also need to play an empty clip audio if the ammo is empty:

void FireLaser()
{
if (_ammoLeft > 0)
{
_ammoLeft--;
_audioSource.clip = _laserShot;
_lastFire = Time.time;
if (_isTripleShotActive)
{
Instantiate(_tripleShotPrefab, transform.position, Quaternion.identity);
}
else if (_ammoLeft > 0)
{
Instantiate(_laserPrefab, transform.position + new Vector3(0, 1f, 0), Quaternion.identity);
}
_audioSource.Play();
UpdateAmmoLeft(_ammoLeft);
}
else
{
_audioSource.clip = _laserEmpty;
_audioSource.Play();
}
}

The end result looks like this:

As you can see ammo is now deducted when it is spent.

--

--