Task: Visualize on screen the ammo count of the player in the form of current/max.
I began by setting up two private int variables in my Player class to track the maximum quantity of ammunition my player could carry and the remaining ammunition stores. I set up the maximum via a variable instead of hard-coding a value to allow future expansion. In my version of the 2D Space Shooter project from Game Dev HQ, I opted to set the max ammunition of my Player to “25”, and I generously started off my player with 20 “rounds” in its stores.
In my UIManager class, I declared a private int to store the max ammunition value from the Player class.
I then called two functions in my UI Manager by caching these int values and updating the UI display at Start().
Every time the Player collects ammo via a power-up, the value of that power-up (ammoCollected) is added to the _ammoCount, and then we call the UpdatePlayerAmmoStores() method.
UpdatePlayerAmmoStores() checks to see if the _ammoCount value is less than 0 and if so caps it at 0 so the Player doesn’t end up with a negative value for ammo. Similarly, if the Player collects enough ammo to fill his ammo stores (set by _maxAmmoStores), then the upper value of _ammoCount is also capped at that value.
Once we’ve established that the Player’s ammo stores are within the legal bounds set by the developer, we then call the SetMaxAmmoCount() and UpdateAmmoCount() methods in the UI Manager to update the UI display.
SetMaxAmmoCount() caches a reference to the Player script _maxAmmoStores into maxAmmo then stores it into _maxAmmoStoresUI.
UpdateAmmoCount() does the same with _ammoCount into ammoCount. We then use this data to update the UI text field.
The entire UpdateAmmoCount() method, which also varies the text color based on remaining ammo, is shown below:
Edit: a better way to set the color code system for ammo remaining is to multiply the _maxAmmoStoresUI variable by a percentage. This will make the UI adapt to whatever the max ammo is in case the value were to change during gameplay (i.e.: ship upgrade).
I hope you enjoyed this quick article. Hopefully, it will help you with your own Unity Game Project. Thanks for reading :)