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 Destroy() 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 Enemy 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,

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 [SerializeField] to easier to adjust.

Then we can make our function Damage() to calculate the damage.

Now our player knows how to get itself destroyed. How to call it from Enemy script? We will need to use GetComponent<>().

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 Damage() which we just created in the script Player.

In this if-statement, if we collide with “Player”, then it will get the component called “Player”(which is the script) and do the function called Damage(). 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.



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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
S.J. Jason Liu

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