Script Communication in Unity

Objective: We will learn how to communicate with other scripts using GetComponent

There are times that we will want to access a script from within a different script. To do this, we will use GetComponent. The only other component you have direct access to from another component is the transform. This will be accessed in a hierarchal way, which means we will access the transform and then get the component within this object. This will look like this:

“other” is getting the stored data from “OnTriggerEnter (collider other)”

This indicates we are accessing the transform of the Player game object in order to get the Player script component. If we want to get a class within the Player script, we will add the class name after <Player> ( )
I’ve created a Damage class within the Player script, telling the console that anytime we take damage, we lose a life, which we need to access since we are currently in our Enemy script. It’s important we make this class public so we can access it from elsewhere.

Damage class within Player script

In order to get this component, we need to add the Damage( ) class to the end of our GetComponent script.

This is getting the “Damage” class from our Player script

Now, in order to clean our code up a bit, we will create a variable for the GetComponent called player.

It is best practice to null check our code, to prevent errors and crashes when playing our game.

As shown above, you can see that I’ve created a player variable for our Player script to fit our GetComponent method within, and I’ve included a null check. This means, our player will only take Damage if the player exists. This will help prevent errors in the instance it is unable to locate the Player script.

Now, we’ve created a communication between two scripts and in this example, we will take damage anytime the enemy attacks us.



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