Script Communication in Unity using GetComponent
From the previous articles we know how to add a behavior to a game object. But it’s about time we learn how to alter or affect behavior of other game objects.
But before we progress any further let’s take a look at our Player game object.
Everything present in the Inspector window is what we call Components, from Transform to Mesh Renderer to Player (Script) to even the Rigidbody.
Phase I :
Let’s start off by creating a method for the Player that other game objects can influence.
Here, Damage() is made public as we want other scripts/classes to have access to it. Also, “x -= 1” is a short hand for “x = x - 1”.
Phase II :
Lets alter the Enemy behavior such that upon contact with the Player game object it deals damage to the Player.
In order to achieve that we will have to add the following in our OnTriggerEnter(),
Where, _player is a reference to the Player type of data. So every component in the project is technically a Type of data.
other.gameObject, this signifies the game object that contains the collider which took part in the collision with the Trigger.
Now that we have the game object we just need to reference the component we require which is done with the help of GetComponent(). Since we require the Player (Script) component, we can pass the Player as the component,
For example, let’s say you want to reference the MeshRenderer component we can create a _meshRenderer variable that stores data of type MeshRenderer and it can be initialized by,
With this we have access to the Player component and we can access all it’s public statements. Damage() is the method we want to influence,
And all of this will only be called if our gameObject’s name matches our Player game object’s name, which is why we added the condition in the if Statement.
Phase III :
Now that we have established communication between the Player and Enemy game objects. Lets add a logic to our Player game object where we destroy the game object when it’s health reaches 0.
This should Destroy your Player game object once its Health reaches 0.
And also add a way for the Enemy to identify the Laser game object when they come in contact with each other.
One way to do this is by using,
The best way to go about this is by using Tag.
With this the Laser component now has a Laser tag. Which can be accessed by doing the following,
Finally, lets add a check to avoid NullReferenceException, this is a runtime exception which usually occurs when trying to reference a variable that is not initialized or referencing any object, and when it happens it is treated as null, which at runtime gives us the NullReferenceException.
The final result looks like the following,
To achieve this behavior the following logic was used,
Player Damage Logic,
Enemy Destroy Logic,
More to come!!!