Limiting Ammo Count in Unity

Harvey Limbo
2 min readApr 16, 2021

For today’s article, I’ll be going over how I limited the number of lasers that player ship can fire. If you’re interested, you can take a look at https://github.com/hlimbo/Space-Shooter-Tutorial to see more of the code in depth.

Modifications to the Player and UiManager scripts need to be made in order to support limiting the amount of lasers a player ship can fire. In Player script I introduced the following 2 variables to keep track of the number of lasers it can fire:

[SerializeField]
private int startingAmmoCount = 15;
private int currentAmmoCount

The [SerializeField] attribute in C# exposes startingAmmoCount in the Unity Editor when the Player component is attached to the player ship. This is useful if I want to later change the starting ammo count to a different value.

Next, in the Update() function of the Player script, I add in the following logic:

Lastly, in the UiManager script, I create the UpdateAmmoText(int ammoCount) function to update the number of lasers a Player can fire that will be displayed on screen as a Text component:

In the above code, $"{ammoCount}" is another way to express ammoCount.ToString(). Placing a dollar sign ($) in front of the double quotes and wrapping the variable name around {} brackets in C# is called string interpolation. It is especially useful for strings that require multiple variables to be outputted as strings. The alternative would be using the + operator to concatenate the variables together (e.g. forcing them into strings by implicitly calling their ToString() functions) but requires the programmer to include a pair of quotes followed by the + operator every time a variable is introduced when building the entire string.

Thanks for reading :)

--

--