My journey becoming a Unity game developer: Phase-45

Objective: Limit the player to 15 laser shots, deactivate the player’s ability to shoot anymore lasers, and turn off the laser sound effects if the player shoots lasers they don’t have.

Final result of the player out of lasers.

Start by going inside the Player script and let’s create new variables to limit the amount of lasers. One variable will be set to the laser’s maximum of 15, and the other will be set to the laser’s minimum of 0. Now set the player’s actual lasers amount given to them at the start of the game to 15 with the variable name laserFire. Also, we will create a Boolean name fireLaser that will turn on and off the player’s ability to shoot lasers.

We already have a reference to the Player’s AudioSource component in the Start() function and an audio clip that plays the laser’s sound when the player shoots.

Let’s head over to the FireLaser() method, we will use the Mathf.Clamp() function on the laserFire variable to actually limit the lasers between 0 and 15 with the variables laserMin and laserMax. Next, create an IF condition that will check if the player can fire lasers using the canFire and firelaser variables. If both conditions are true, then all the code inside the method will be executed.

We will add 2 extra things inside the code. The first is a Debug.Log() to print out the lasers in real-time to see if the amount is decrementing properly. We will add it right before the laser sound clip plays using the laserFire variable. The second thing is to create another IF condition which will check if the player’s laser amount is less than zero. If it is, we will use the StopShooting() method which will turn the fireLaser variable off to keep the player from shooting and we will also turn off the laser sound clip by using the audioSource.Stop() function.

Player’s lasers are limited and turned off when they’re below one.
Final result of the player out of lasers.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store