How do you get the player to call their damage function when you are the enemy? In Unity, we can call the public function on another script with script communication.
Let us use the example above. When an enemy and player collide, we generally want to reduce the health of the player.
What if the player also needs to play an audio clip and shake the screen when they get hurt? We would generally make the player's health variable private and force all damage to be caused through a damage function.
How to use GetComponent?
This is where script communication comes in. First, we need a reference to the object. We do this in a lot of different ways. In our example, we can cache the collision information (stored in “other”) and use the method “GetComponent” in order to get access to our player script which has the damage function we want to call.
GetComponent<> allows you to pass in a component and have access to all public variables and functions. See below that our player's damage functions causes text to appear on the screen when it is called.
How to find an object?
What if we need to access another game object that we have not had a collision with? Let us say we have two enemies and want to turn an enemy aggressive and change their colour to red if they witness the death of their teammate. They already have an Aggression public method that has this functionality, so we just need to call it.
This is where we can use “Find”. You can find an object by a multitude of different identifiers (name, tag, etc.) and if you find them you can then access their components using the get component call.
In our method, we are going to try to find our teammate (by tag) and call their Aggression function. First, we are going to make a generic variable (called teammate). Next, we need to find our teammates and assign them to this variable. We can then get the enemy component (script) from our teammates and call their aggression function.
As you can see once the first enemy is destroyed we use script communication to call the aggression function on our other enemy.