Script Communication in Unity using GetComponent
For today’s article, I’ll be going over how I get other scripts to communicate with one another using GetComponent<T>
. Based on the Unity Docs, GetComponent<T>
allows the given game-object grab the component it may have attached in the Unity Editor.
Getting Components from Start() or Awake() methods
One common way I retrieve components from my game-objects is by storing a private variable in my MonoBehaviour script and grabbing the component on either Start() or Awake(). I do this because it allows me to cache the component reference and use it in other Unity lifecycle methods such as Update().
Getting Components from OnTriggerEnter2D(Collider2D other)
Another way I retrieve components is by accessing the other collider2D:
In the code above Collider2D other has public access to the method GetComponent<Player>()
which allows me to retrieve the other colliding game object that triggered this event from occurring. Alternatively, I could have written other.gameObject.GetComponent<Player>()
but other.GetComponent<Player>()
is much shorter to type and is my prefer way of getting components in this context.
The only pitfall of using GetComponent<T>
where T is the type of Component being retrieved is that the component may not be attached to the game-object. In this case, I do a null check to ensure I don’t run into NullReferenceException
.
Thanks for reading :)