Unity: Implementing Player Ammo, Part 2
In the first part of this article we implemented limited ammo for the player, but this left them with nothing to fire before long. Let’s add a collectable to reload the ammo.
First off, I want to quickly add a sound to indicate when the ammo is zero.
In our Player.cs script I’ve added another audio clip to be assigned in the inspector. Inside the FireWeapon() method, when the ammo is zero, we now also assign the out of ammo clip and play it.
For the collectable, I have duplicated one of the existing powerups in Unity and added a new icon. I have created a new script, Ammo.cs as I want the ammo to be on it’s own, separate timer from the power-ups:
This behaves in much the same fashion as the power-up script but instead of having a power-up ID, this will be it’s own entity that will spawn independently of the other boosts.
We also have a further audio clip which plays when the ammo is collected. This will help it stand further apart from the other power-ups.
The main point to note is that it calls UpdateAmmo() on the player when the collision is detected:
Over in our player script we now call the UpdateAmmo() method and pass the ammo adjustment (negative or positive) whenever we need this to change. This also updates the UIManager.
We now call this from Start() and FireWeapon() within the Player class as well.
Finally in the SpawnManager.cs script, we add variables for the ammo collectable prefab and the ammo spawn delay.
We create a new SpawnAmmoRoute() coroutine which is called in StartSpawning(). This will allow us to control the rate at which ammo spawns separately from the other power-ups.
All we need to do is assign our various elements in the inspector and we can now allow our player to reload and not be left out in space with nothing to fire!