Dev Day 51: Limiting the Ammo Count in Unity3D

Objective: Limit the Player’s available ammo count to a maximum of 15 laser shots. However, the Triple Shot Power Up laser shots will not decrement the ammo count and will be able to be utilized even if the Player’s ammo count is 0.

Step 1: In Unity, create a Text GameObject within the Canvas GameObject in the Hierarchy window called Ammo_Count_Text and position the text box to the desired location on the screen with the desired font properties.

Step 2: In the Player script, create a private int variable called _ammoCount, using [SerializeField], and assign it a value of 15.

Step 3: Create a private variable of type Text called _ammoCountText.

Step 4: In the Start() method, use GameObejct.Find to find the Ammo_Count_Text GameObject, access the Text component, and assign it to the _ammoCountText variable. Null check the _ammoCountText variable and then assign the UI display text for the ammo count, which is: “Ammo: “ + _ammoCount, to the Text component of the _ammoCountText variable.

Step 5: Create a private bool called _isAmmoEmpty and have it equal to false.

Step 6: Create an if statement to instantiate the single-shot laser beneath the Triple Shot if statement. Within the new if statement, if the _isAmmoEmpty bool is equal to false and the _isTripleShotActive bool is equal to false, then instantiate the Laser Prefab, decrement the _ammoCount variable, and update the Text component of the _ammoCountText variable to the updated ammo count.

Step 7: Within the instantiate laser if statement, create a new if statement stating that if the _ammoCount variable is less than or equal to 0, set the _isAmmoEmpty bool to true, which will disable the instantiation of the single-shot laser.

Now, the Player’s available ammo to limited to 15 shots, and each time the laser is fired, the UI display will update the current ammo count. And since the _isTripleShotActive bool must be set to false for the ammo to be decreased, the player can use the Triple Shot Power Up without decrementing the current ammo count and even if the ammo count is depleted.

Unity Developer