Giving the Player Limited Ammo
So far in Galaxy Shooter, the player has been able to fire lasers infinitely, without a care for how many times he misses. To add more challenge to this game, instead we will only give the player a limited amount of laser shots. They will have to be careful to conserve ammo, or pick up an ammo powerup that will replenish it.
Of course, we don’t want this ammo system to be invisible. We’ll need a text object in the UI to display how much ammo is remaining.
There’s absolutely no shame in making a very simple text-based UI for this! If we want to replace this with graphics later, it will be very easy to do so because all the systems to support it will already be in place.
The Player script handles firing lasers, so we need to change some things there. It will need variables to keep track of the maximum ammo as well as the current amount of ammo. The maximum ammo is serialized so it can be changed in the inspector, which will allow us to fine-tune the ammo count later.
Now the Update method is changed. In particularly, we want to add a new condition so that the player’s laser can only fire if they have more than zero ammo.
Now, inside the FireLaser method, in addition to creating a laser and sound effect, we also reduce the current amount of ammo by one. Then we tell the _UIManager to update, so the text we made for the UI is edited to reflect how much ammo is remaining.
We shouldn’t need to prevent _ammoCurrent from going below zero, since the laser won’t be able to fire at zero ammo anyway.
This GainAmmo method is called in Start, and would also be called if the player were to touch an ammo powerup. This will ensure that the player starts with maximum ammo, instead of zero ammo.
Now the UIManager class. It requires variables to keep track of the text object and whether or not the player has run out of ammo.
This is the new UpdateAmmoCount method that is called by the Player script. This will update the text to show how much ammo is remaining. Also, if the ammo count is zero, then it will start a coroutine that will cause the text to flash red. _ammoEmpty will be set to true or false in order to control when the coroutine ends.
Finally, here is the AmmoEmptyRoutine that is started when ammo is zero. We can re-use the _textFlashDelay variable from when we made the flashing “Game Over” text, so that the ammo text also flashes in the same way.
All done. We now have a simple ammo system and a simple UI element to go with it. This is very basic but can be very easily expanded later, or we could change the UI to add graphics to represent ammo. We even a public method already set up so the player can utilize an ammo powerup. That will be the topic for next time.