2D Galaxy Shooter P1: Adding Ammo Count!

Gabriel Perez
2 min readApr 26, 2021

Today’s challenge is to add an ammo count when firing!

Hello everyone! The objective for today was to implement an ammo count when firing.

So the first thing I did was add a couple of variables to determine the ammo count and max ammo count.

These are the variables I initialized and declared of type int:

[SerializeField] private int _ammoCount = 0;
[SerializeField] private int _maxAmmoCount = 15;

In the Start() function, I added:

_ammoCount = _maxAmmoCount;

It allows us to start the game with the max amount of ammo.

The next thing is to add logic before the shooting starts. I want to negate the ammo count every time I fire. I also want to clamp the ammo count when it reaches zero.

In my Shoot() function, before any code, I add:

if (_ammoCount == 0)
{
_ammoEmpty = true;
_ammoCount = 0;
_audioManager.PlayAmmoEmptySound();
return;
}
else
{
_ammoEmpty = false;
}
_ammoCount -= 1;

If the ammo count equal to zero, the ammo is empty. We also want to clamp the count to zero so that the value won’t go negative. We also want to play a sound for when we have no ammo. And finally, we want to return; so we can skip the remaining code until we somehow find more ammo.

It all works great! I also went ahead to find an ammo icon for the UI. I needed to show an indication of how much ammo we have for the challenge. Here is the result.

Now that we have an ammo count, we need to add a way to restock ammo! That will be for tomorrow's challenge.

Thank you for your time!

--

--

Gabriel Perez

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.