My 120-day journey to being a better Unity Developer — Day 12
Script Communication in Unity using GetComponent
Objective: When a player touches a coin, have the coin let the Game Manager know to increment the coins collected amount.
In my last article, “OnCollisionEnter Vs. OnTriggerEnter — When to use them?”, I went over the difference between OnCollisionEnter and OnTriggerEnter and explained an example. I thought let’s put that example into action by using the GetComponent method.
In this scenario, we have a case where we need to set up communication between two scripts, and the way we do this is by using the GetComponent. Firstly, let’s break it down into pseudocode.
When a script needs to get information from a component attached to a game object, it needs to use the GetComponent method. A script is also a component, a custom component.
In my scene, I have a GameManager game object with a Game Manager script, a coin prefab with a coin script, a player with movement, and a basic level.
In the Game Manager script, there is a public method that increments the coins collected. This is what the Coin script will call when the player touches the coin. Note the CoinCollected method is Public o other classes can access it.
Now how does the Coin script talk to the GameManager script? There are a number of ways to tackle this and in this article, we will use the GameObject.Find a method to first find the GameManager game object and store a reference to its GameManager script component.
It is often good practice to call it in the Awake or Start functions or only once when it is first needed. It is also a good idea to check that the GameManager instance is not null, as in, it was found.
In the OnTriggerEnter, we check if the game object that comes in contact is the player and then we call the CoinCollected method from the GameManager script as well as make the coin disappear.
Once the CoinCollected method has been called the GameManager updates the information on the screen (UI) to reflect the coins collected by the player.
FINAL
CODE
If you enjoyed reading this article give me a Clap, also if you want to see more like this, “Follow” me, so you may be notified of future releases. You may also send me a message if you need any further help.