Using GetComponent in Unity
Get Component — the easy way to have scripts communicate with each other in Unity.

Why use it?
Let’s say we want to update player stats such as player health or score in a UI object. Let’s assume we already have a player and a UI script. GetComponent will allow us to access the UI script from within the player script.
Setting up a variable
We first need to create a global variable in the script where we want to access the other script. Here it is the player script.

This variable will store the UI Manager script, so that we can access it easily from the player script.
Getting the component
Once the variable is created, we now need to find the script and get the component. Our UI Manager script is attached to the Canvas game object in Unity.

Once we know where to search, we can grab our UI Manager script and store it in the variable _uiManager. We do this in the void Start() method.
Here is what the code looks like:

So let’s have a look at the syntax. We ask the program to find the object “Canvas” of the type GameObject, then we tell it to get the component <script> called UI Manager.
var = GameObject.Find(“Name GameObject").GetComponent<script>();
If the component is not found, then null is returned. Thus it is good practice to check if the component is available and add an entry into the debug log if it is not.

We can now access the UIManager script from within the player script.
A warning

It is important to notice that GetComponent is expensive. Doing so too often will have an impact on performance.
Enjoying the results
The two scripts can now communicate. I can, from within the player script update the UpdateScore function of the UIManager by passing the _score value.

And the Update Score allows me to display the new score in my text object called _scoreText.

So now the player can enjoy seeing their score. And all of this because GetComponent allows those two scripts to communicate.
