14-Player Damaging and Lives — Script Communication using “GetComponent”
In the previous update, when the enemy collide with the player, we had the enemy destroy itself, but nothing happened to the player yet. Here, let’s take life off the player when it get hit by an enemy. Here is the flow of thoughts to make it happen:
- The player needs to have lives, which will be subtracted each time it gets hit
// define life variable
// define a PUBLIC Damage method that subtracts the life
* the Damage is made public so that it can be accessed by the Enemy script when collision with player happens
- When all the lives are taken, the player will be dead (player game object gets destroyed)
// if life < 1
// Destroy player
The biggest challenge here is to have the Enemy script talk to the Player script, that it, call the Damage method in player. To have access to the Player script, we need to get a reference of it using the GetComponent method in Unity.
It should be noted that we can not directly access the <Player> component (i.e., other.GetComponent<Player>()) will not work. Instead, we need to go to the root (other.transform) first, that is, other.transform.GetComponent<Player>(). This is because the only component we can directly access is the “transform” component, and every gameobject has a “transform” component.
Whenever we get the component, it is a good practice to do a null check to make sure that component is accessed successfully before taking an action.
Now, when the player gets hit by the enemy three times, its life will drop to zero and disappear from the scene.