Ammo!!! I’m out!!!
Objective: implement an ammunition count system in your game project which limits your firepower capacity, leaves you vulnerable if you run out, but allows for powerups to regenerate your ammo stores.
So here’s my scenario: I want to start the Player’s ammo count at 25 shots. Every time the Player fires, the ammo count gets reduced by 1. Once the Player’s stores are expended, the Player should no longer be able to fire its weapon, and the ammo count needs to remain at 0 until the Player is able to collect some ammo via a randomly generated powerup. As the ammo count drops, there needs to be some sort of visual cue that warns the Player that his ammo state is becoming critical.
Let’s start by adding the following private int _ammoCount and setting it to 25 in the Player script.
Then, in the PlayerFiresLaser() method, add the following at the top of the method. This will check the value of _ammoCount. If _ammoCount is above 0 and the “cooldown” is true, only then can the laser weapons be fired. If both these conditions are true, then the _ammoCount int is reduced by 1 shot and we call the UpdatePlayerAmmoStores() method.
The UpdatePlayerAmmoStores() method sets the clamps for the ammo stores. If the value becomes negative, it is set to 0. If it tries to go above 25 (which is the max quantity I opted to use for my version of the game), then the _ammoCount is capped at 25. Once this has been checked, we take the new value of _ammoCount and pass it to the _uiManager via the UpdateAmmoCount(_ammoCount) method.
In the UIManager script, add a new private Text Mesh Pro text field to represent the Player’s ammo count.
In the UIManager script, add a method called UpdateAmmoCount(int ammoCount). This method looks for the int representing the remaining ammo held by the Player. This int variable, ammoCount, is set by the value represented by _ammoCount in the PlayerFireslaser() method of the Player script.
Through script communication, the ammoCount is passed from the Player script to the UIManager script when the UpdateAmmoCount(int ammoCount) method is called.
In the Canvas, duplicate the Score_text, rename it to Ammo_Count_text, change the “Score: 0” text to “Ammo: 25”, reposition it in the game scene, and set its color to bright green.
Now, go back to the UpdateAmmoCount(int ammoCount) method and add the following IF, ELSE IF statements. These will change the text color to yellow if the ammo count is equal to or less than 15, but higher than 5. Similarly, if the ammo count falls is equal to or less than 5, the text color changes to red indicating a critical ammo state. Anything above 15 will have a green text color.
The result is a subtle warning as the Player’s ammo gets depleted. You could experiment further and expand with an audio cue or a larger warning message flashing across the game scene. I hope you have found this article interesting, and that it will help you in the design of your own project. Thanks for reading :)