Script Communication in Unity using GetComponent

When we’re working with different systems in games is a Good Practice to have everything separated. But how do we communicate different scripts in Unity?

C# class instantiation

Inside c# the way we interact with classes is by instantiating objects. Let’s take a look:

In this example, we can see how our program is creating a student called lucas aged 15… as simple as that.

But…

As far as we’re working with components inside Unity isntantiating the Class is not the right way to handle communication between scripts. ‘

So what can we do?!!!

GetComponent is our Hero!

Now, imagine we want to reference the Rigidbody class from the Unity’s physics system… let’s try it.

You should not to this

If we made it in this way, Unity will throw us the next error…

Here is when GetComponent joins the party!

This one(Image above) is the right way to call scripts that inherits from MonoBehaviour in our Unity projects!