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 PlayerScript.
Then, in the PlayerFireLaser() method, add the following at the top of the method. This will check the value of _ammoCount. If _ammoCount falls to or equals 0, then the min value is clamped at 0 and you exit the method.
Exiting the method at this point removes the Player’s ability to “fire” its laser.
If _ammoCount is above 0, then you simply reduce the total ammo held by 1.
In the UIManager script, add a new private Text Mesh Pro text field to represent the Player’s ammo count.
Now go back to PlayerScript and add a line to the PlayerFireLaser() method in order to access the UIManager and update the ammo count every time the total ammo held by the Player is deducted by 1 “shot’. Then take the new value of _ammoCount and pass it to the _uiManager via the UpdateAmmoCount(_ammoCount) method.
In the UIManager script, add the following 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 PlayerFirelaser() method of the PlayerScript.
The int ammoCount is passed by the PlayerScript by the private int _ammoCount 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 to your liking, and set the default color to bright green.
Now, add the following IF, ELSE IF statements to the UpdateAmmoCount(int ammoCount) method. This will check to see if the ammo count falls below 16 but remains above 5. If that is the case, the text color will change from green to yellow. Similarly, if the ammo count falls below 6, the text color changes to red indicating a critical ammo state.
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 some benefit in the method I used, and that it will help you in the design of your own project. Thanks for reading :)