There are a variety of methods that allow scripts to communicate, but this article will focus on using the GetComponent method in Unity.

But first — why do scripts need to communicate?

Typically, all variables and methods in C# scripts will be set up with the private access modifier to ensure no other scripts are able to make changes. For example, if you have a script that tracks the points earned in the game, you might have a private integer variable to hold the points value as it increments. However, to allow other scripts to increase the points value, you could create a public method that increments the points value by 10 each time it’s called. To allow an enemy’s script to be able to call that public method as the enemy is destroyed, your enemy script would need access to your points script. So, let’s dive into using GetComponent for script communication.
How to use GetComponent
Before you can use GetComponent, your active script first needs a reference to the other GameObject you are looking to communicate with. This can be done in a variety of ways, including but not limited to:
- using GameObject.Find() to search for an object in the scene by its name
- accessing the other object in a collision using the Collider or Collision object in Collision or Trigger methods
- declaring a variable to hold the reference and assigning the object in the Inspector

Continuing with the prior example, to update the point value and display it on the screen, the active script will need access to the Canvas object where the DisplayPoints script is attached. With the code above, we are looking for an object named “Canvas” and caching a reference to that object. Additionally, we are checking to see if the Canvas object was successfully found by checking whether or not the _canvas variable holding the reference is null.

Once we have a reference to the object containing the script, we can use GetComponent to access the script on that object and cache a reference to it for future use. Using dot-notation, we can call GetComponent as method of the cached object. In between the angle brackets (< and >), we can enter the Type of component we are looking for. To access the MeshRenderer to change the other object’s color, you would enter MeshRenderer as the Type. When getting a script component, you enter the name of the script, as this is the name of the class the script defines (ie. DisplayPoints). Same as before, we’ll null-check to ensure the script was successfully found and cached to avoid future errors.

Now that our Enemy has a reference to the DisplayPoints script, we can update the OnTriggerEnter method to call the public AddPoints method from our DisplayPoints script when the Enemy has a trigger collision with a Bullet.

What can you do when your scripts communicate?