Learn to code by making a 2D space shooter game.
Objective: Implement Ammo count.
The first step lets create an int variable called total lasers inside the player class and initialize it equal to 15.
The second step creates another int variable called current lasers.
Go to the start say current lasers are equal to total Lasers.
The next step creates a method called ammo count with parameters, inside the player class.
In the next step decrement currentLasers by the amount parameter inside the Ammo Count method.
To make sure the current Laser never passes zero, let us check if the current laser is less than 1 assign it to zero.
Now we need to fire only 15 lasers and when lasers are empty we need to stop firing, we do this by checking if the current Lasers is greater than zero we fire the laser.
Let's see the result
To make ammo count display on the screen, let's create UI Element text inside the canvas and position it on the left below lives Image and rename it “Ammo: 15”.
If you don't know how to set up the UI text elements here is the article link:
In the next step go to UIManager script create a Text variable called ammoText.
Then Initialize the ammo text dot text to “Ammo:” increment with 15 in the start method to make sure when the game starts our Ammo is 15.
Go to hierarchy < Canvas<Ammo_Text, hold and drag Ammo_Text to the field in the inspector of UIManager field called ammo text.
In the next step create a Public method called UpdateAmmo which pass parameter inside UIManager.
Now let's increment AmmoText dot text with a parameter, this will allow us to update ammo when we call it.
Last let's call the Update Ammo method inside Ammo count after we decrement current lasers.
Note: Before doing anything we need to check if UIManager is not null, check my other article about Mastering script communication.
Let's see the final result.
See you in the next article.