My 90 day journey becoming a Unity game developer: Day-7
Objective: Continuing with our player and enemy prototypes, we will add damage to our player and destroy the player when they lose all of their lives. Here will be the final result:
Open your Player script, create a variable called lives and assign it a default of 3. After that we will create a method called Damage(), where every time we get hit, we will lose 1 life. Also, if we lose all our lives, we will destroy the player game object. Here is the following code:
Next we will go inside our Enemy script and to the OnTriggerEnter() method. Inside the Player’s tag code above the destroy this game object code, we will get the player’s component to access the Damage() method.
Let’s make this code more readable and accessible by creating a variable called player to get the player’s component.
Finally, before we call upon the Damage() method from the Player’s component, we should do a NULL reference check on the Player. This is considered good practice to do because this will prevent the game from crashing if the Player’s component is not available.
We now have it set up where the player dies after colliding with the enemy 3 times. Next time we will work on creating a spawn manager for our enemies to come out and attack the player. See you then …