Unity3D: Using GetComponent for Script Communication
The GetComponent function allows us to communicate with other components in the same game object or another.
Here’s an example of a player script with a lives variable and a public method to take damage.
Eventually, the player will need to take damage at some point from an enemy.
Let’s take a look at the enemy script with an OnTriggerEnter()
function with a condition to check if the other collider is the player by tag.
We want to communicate with the player so that when we collide with the player, we can damage the player and destroy the enemy game object. Checking the tag of the player only checks just that. It doesn’t provide us a solution to communicate with the player.
So we need to find the Player through the use of “GetComponent.” Since we are checking collisions with OnTriggerEnter(Collider other)
, we can use its parameter other
to grab information about the game object this enemy has collided with.
We can cache this line of code into its own variable of type Player so that we can clean it up.
We can now call the public function “TakeDamage” in the Player Example script by using the player variable where we stored the information.
We can now communicate with the player from the enemy script by using the GetComponent<type(the script you want to access)>()!
That is all for today, everyone! Thank you for reading.