Let’s add some player ammo
Now that we have some thrusters on our player, which we talk about here, we will now look into adding an ammo system today. First, we will look into how to get our script set up so that when our player shoots the set amount of shots, which in this case will be 15, we stop firing. In a future article, we will look into creating a new powerup that will replenish our ammo count.
To start, we need to create a couple variables on our player so that we have something to call upon for our script:
We will place these 3 variables into our player script. Within our void start, we will code in ammo = _maxAmmo so that when we start our game, we are at 15 shots. Next, we will go to our FireLaser method and state that if _ammoDepleted = false, FireLaser:
With this code, we will not be able to fire anymore once our ammo has been depleted, however for it to work, we need to create an if statement so that we know when our ammo is depleted:
Now that we have this all created, we can test our game to see if we stop firing after 15 shots and the debug.log shows up:
Now, we have to create an UI indicator so that we know how much ammo we have, and to flash us an indication that we have no ammo. First, we will go to our UiManager script and create a couple new variables to work with:
From here, we will create a link to our player script like we have done before with the gamemanager so that we can pull information from it, along with the initial script for our game to show our ammo count with:
Now that we have our initial script created, we can create a new public void for our script to have our text run from and stay updated with our current ammo count:
Just like what we did with our Score text, we have our void text attached to our player method, which we will also have to create on the player script:
Now that we have everything scripted into our UIManager and Player scripts, we can go back to our Unity editor and see if it runs like we want it to:
And there we have it. We have successfully implemented an ammo system so that we can limit how much our player shoots so that he doesn’t just fire endlessly. However, the issue is now how do we give our players ammo to replenish their supplies. As to how we will solve that problem, we will do that in a future article.