Player Lives and Damaging Systems in Unity!
In my previous article, we went over OnTriggerEnter() that will destroy the player and enemy when collided. To make this game more exciting, I would like to introduce the ‘Player Lives’ and ‘damaging’ systems — Initially provide 3 lives for the player & loses one by one when collided with the enemy.
Damage() method in Player Script
First, let’s create a variable ‘_lives’ with the value of 3 in the player script.
Then, at the bottom of the script, create Damage() method that will
- lose 1 life each time when this method is being called.
- Create an if statement — if lives reach 0 (or less), we will destroy the player.
That’s all we need to do for the player. Let’s go to the next step.
GetComponent<>
In Enemy script, we previously created OnTriggerEnter () method that will destroy the player instantly.
Remove this code line ‘Destroy(other.gameObject);’, then add ‘other.GetComponent<Player>().Damage();’.
- GetComponent<> will find a specific component that is attached to the game object called in <>. In our case, we are looking for a script component called, ‘Player’, then look for Damage() method within that script.
As you see above, each time when an enemy collides with the player, the lives reduce down by 1. Then, destroyed when reaches 0.
Null Checking
It may appear that we are all done, but there is one last thing that we should do — Null Checking.
There may be a time that this player script is turned off or removed by accident. And, if we just run this game and when OnTriggerEnter() method is being called out, we are most likely going to face an error or crash.
To avoid this, it’s a good idea to implement Null Checking with if statement.
- create a variable called ‘player’ that will store the player component.
- create an if statement: if the variable ‘player’ is NOT null (null = zero or nothing). In short, if the Player component is found, call the Damage() method.
Awesome! That wraps up the Player's lives and damage system. Thank you so much for reading!