Contact to Other Scripts with GetComponent- Game Dev Series 10

Try to communicate between scripts with GetComponent command.

Previous: Collision or Trigger?

Now our player is able to eliminate the enemy but how should enemy do to the player?
The function is simple, just take the game object away from game. If the player would be destroyed simply by one collision, that would be too hard(well, some game really do in this way). We can make our player get some damage after the collision if we can run the function from the command of script.

To make a damage on our player, we need to create a method for it.
Open the Player script and add another function for dealing damage,

public void Damage()


This function would be called by other script, that is why it need to be a public function.
Before that, we need to make a variable for counting the damage. We can create an integer as lives count. And also give a to easier to adjust.

private int _lives = 3;

Then we can make our function to calculate the damage.

Now our player knows how to get itself destroyed. How to call it from script? We will need to use .

A C# script is just like a collider or a mesh renderer, is a component from game object, which we can easily to locate.

Back to our enemy, when we collided with player, we need to call the function which we just created in the script Player.

In this if-statement, if we collide with “Player”, then it will get the component called “”(which is the script) and do the function called . Then our Player should deal 1 damage.

We also can make a variable to storage the component to make our script cleaner.

Furthermore, we can add another if-statement to prevent in some situation it might accidentally remove or change the Player script and cause some error.

Now the enemy should have a fully function on collision.
Let’s Play and see the result.

You can see the lives countdown when collided

A passionate gamer whose goal is to work in video game development.