Script Communication in Unity using GetComponent

Sean Kaleomaikalani Ferreira
2 min readSep 27, 2023

--

Another day another script to write, but this time you want something more. Maybe you need to communicate something between objects, like a function that’s in one script needs to be called by another script. In that case, you need GetComponent

“GetComponent” is a multi-purpose function that can point to another object’s component (like their script or their mesh). In our example today we will just be grabbing the script of an object called SpawnManager.

First, make sure you have a new variable to store your information (like a “Player” would be stored in a “Player” variable). Then type in an equivalent to the picture above.

variable_name = GameObject.Find(“name of the GameObject”).GetComponent<name_of_component>();

Don’t forget to Null Check!

There is a safety practice known as null checking, which basically makes sure that the code actually grabbed something. If nothing is grabbed, an error is thrown letting you know that the GetComponent failed. It is also common practice to GetComponent in the Start() function due to it’s high processing cost.

With that, you now have a functioning variable for another script or any other component on another object! When you want to access another object’s script functions, just start with the variable name, then ‘.’ and the name of the function!

--

--