Communicate Between Scripts in Unity with GetComponent()
Frequently, in Unity development, we need to access another running script from our current script. An example being the need to damage the player’s life when they collide with an enemy of some type. This can be done fairly easily using the GetComponent method in Unity’s GameObject class.
Before we jump into any code, let’s answer a simple question. What is a component in Unity? A component is something that provides functionality to your game objects in Unity. Examples of components are things like transforms (which are found on all game objects), rigid bodies, and mesh renderers among many, many others. For a more detailed read on components check the Unity documentation here:
In the inspector window here you can see the player game object has a transform, a mesh renderer, a box collider, and a player script. These are all examples of components on an actual game object.
Each of these components can be accessed in code, all we have to do is get a reference to them and we can easily do that with GetComponent.
So how do we cause our player to lose a life when they collide with an enemy? The Lives variable you see to the left resides inside the Player script attached here.
When we have determined that the enemy has collided with the player, we can access the Player script as shown below. The line with GetComponent<Player>() is where the work is done. This will store the reference to the component in the player variable declared earlier on the line. After that you can invoke any public methods in the player script as you normally would. Here we call player.Damage() to remove a life from the player. Also, be aware that other.transform gives us access to the player game object itself as the “other” is a reference to the player’s collider component.
Aside from accessing components on other objects, we can also use GetComponent() to easily get references to components on our current game object.
The following code illustrates how we can grab a reference to the Mesh Renderer component on the same object as our script:
This will reference the Mesh Renderer on the current object.
As you can see using GetComponent<>(); is a straightforward and simple way to communicate between scripts and obtain references to components. Knowing how to use it is really a pre-requisite to any serious Unity development.