Script Communication in Unity using GetComponent
When programming, our scripts need to interact with one another, have references to game objects, and move data around efficiently. In this article, we will explore how to effectively communicate between two scripts using GetComponent.
Imagine you want to access a variable or method from Script A, and call it from Script B. In order to do this, we need to create a reference to the desired script.
In the following example, Beam is the actual name of the script, and _beam is the variable where it gets stored. This variable is going to be global and initialized in Script B(the script that wants to access the other script).
To use the script, you will need to find it within the object to which it is attached, this is where GetComponent comes in. The GetComponent function searches the designated object for a component that matches the type we specify. If no such component is found, a null reference is returned.
This search is performed in the void Start() function.
Best practice tip: You should always check if a component is available, this if statement will show an error log message if the component can’t be found.
With your reference set, it’s time to access the script. This can be done simply by typing your reference variable followed by the name of the method you are trying to call.
In this example, the aforementioned script communication was used to call a method from the Beam script if the user presses the space key.
In the next article, we’ll be taking a look at coroutines!