Limiting the Player: an Ammo System (Game dev Day 35)
Objective: Limit the player’s ability to fire by requiring ammo. Create both a visual and audio feedback system to alert the player of their ammo count.
Currently, the Player is free to fill the playing area with proverbial lead (lasers in our case). However, that is not indicative of refinement, and we can add a mechanic that requires the player to ration their offensive ability.
First off, we need to establish what “ammo” is to the game. We start by creating a new variable in our Player script.
Now, when do we use ammo? When we fire our laser! So if we look into our FireLaser function and determine when the player should lose ammo.
So now when we fire a normal shot, we subtract 1 from whatever _ammo’s current value is.
Now what happens if the player is out of ammo (or _ammo == 0)?
No projectile is fired, and we play a sound effect to alert the player to their conundrum. We need to implement a few more things to get that audio working however, so let’s tackle that next.
We need to add that _audioSource2 variable to our script, as well as the sound effect itself.
Go back to Unity and add a new Audio Source to the Player (at this point I have 3, one for laser, one for no ammo, and one for picking up a powerup).
Add the sound effect you want to the “No Ammo Sound Clip”, and then add it again to the new Audio Source’s AudioClip slot. It should look like the above picture.
Now we need to go back to our script and determine when this new sound should play. It will fall into the “if (_ammo == 0)” part of our FireLaser function.
Great! Now the player can here a sad “clink” when they have no more ammo, but we can do better than that. Let’s add a UI element to display the current ammo count at all times so the player can better determine when to fire.
First, we need a new UI text object, and we need to place it as a child of our Canvas Gameobject (just like every other UI piece).
Next, lets change the color from grey to a bright green in the Inspector.
We will also add the beginning value of the ammo (15)
I positioned my Ammo counter right below my score output in the game window.
Now we just have to link everything together and add some simple math to our code.
First, we need another variable, this time in our UIManager script for the Ammo text object.
Next, we need a function to change our ammo count. A simple example is as follows:
Remember that we already have the subtraction of the ammo in our Player script. So lets add this new function to our player script right after we subtract the ammo.
Last but not least, we need to drag and drop the Ammo Text object into the UIManager script’s variable for it.
And voila! There is now visual and audio feedback alerting the player of this mechanic. A visual demonstration can be seen below.
Next, shooting on 0 ammo will not produce a laser.
Finally, a short video to show the new sound effect.