Working with Return Methods in Unity3D

Pete Thomasberger
3 min readJul 26, 2021

--

Objective: When pressing the space bar, damage the Player by a random amount and, using a Return Method, check if the Player has died. If the Player has died, print out “The Player has died!”, do not let the Player’s health drop below 0, and prevent that the space bar from causing more damage.

Step 1: In Unity, create a 3D Cube in the Hierarchy window and rename the cube to Player.

Step 2: Create a C# Script called Player and attach it to the Player GameObject in the Hierarchy window.

Step 3: Within the Player script, create a new public variable of type int named health, and have it equal 100. This will represent the total health for the Player.

Step 4: Within the Update() method, create an if statement for pressing the Space key.

Step 5: Create a new private method called Damage() with an int parameter called randomDamage.

Step 6: Within the if statement in the Update() method, call the Damage() method and pass in a range of damage from 1 to 100 that will be triggered randomly when the Space key is pressed.

Step 7: Within the Damage() method, now that the randomDamage parameter is equal to a random range of 1 to 100, have the health variable be equal to health minus randomDamage.

Step 8: To check whether the randomRange has killed the Player, create a private return method of type bool call IsDead(). Within this method, state that for the IsDead() bool to be true, the return must be that the health variable is less than 1.

Step 9: Within the Damage() method, create an if statement stating that if IsDead() is true, then the health variable is equal to 0, which will ensure that the Player’s health does not become a negative value, and then print out “The player has died!”.

Step 10: Lastly, to restrict damaging the Player after IsDead() is true, add an additional condition to the if statement in the Update() method stating that IsDead() must be false for the Space key to cause damage.

Now, while the Player is alive, the Space key will generate random amounts of damage until the Player’s health is less than 0. At which point, the Player will be recognized as dead with a health value of 0 and “The Player has died!” will be printed to the Console.

--

--