Day 9: Script Communication in Unity using GetComponent

When you need two scripts to communicate, each game object is provided with a method of searching for components related to that object by knowing its type. We are talking about GetComponents.

This tool is a function of each game object that is used to call one of its components to get access to its public data/variables and methods.

Between the brackets <> we insert the type of component we are looking for.
In our case, we are looking for the script of the player that we have already written previously.
We allocate it in a variable of the same type otherwise we will get an error on the console.

You can call a component temporarily to access its data, or you can store it in a variable within your script. You can also do this on other components within your game object.

When we use a Rigidbody instead of passing it from the Inspector we can call it in this way.

According to your needs, you can use it, but be careful, if you need a component many times it is better to store it in a variable to be able to reuse it later, instead of doing it every time.

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