Script Communication in Unity Using GetComponent

Chris Hilton
3 min readJun 18, 2021

--

Objective: To get our scripts to talk to each other using GetComponent<>() within Unity.

I want to now be able to implement a Player Lives and Damage system within my Galaxy Shooter so that when the Enemy and the Player collide with each other, the Enemy should get destroyed but the Player should remain and a live should be deducted from it’s total lives. In order to be able to do this, I would like to implement a Damage() method into my Player script that also talks to the Enemy OnTriggerEnter() method in it’s script.

Currently we can’t access components in the Player script from the Enemy script (apart from the Transform). Best practice is, we also don’t want to directly modify/change a variable directly in the Player script otherwise it could lead to unexpected and unnecessary changes.

The solution to this problem, is that I am going to create a Damage() method within my Player script that handles the Player lives system and is called upon from within the OnTriggerEnter() method within the Enemy script. Let’s get into it:

Player script:

Damage() method within the Player script

Enemy script:

Using GetComponent<>() to access the Player script from within OnTriggerEnter() method

Refactoring

Now, if you haven’t used GetComponent<>() before, the method itself can be quite taxing on the performance side of things as it is constantly trying to get the component from another script and keep null checking before it runs the Damage() method EVERYTIME it collides. There is a solution to this! Let’s just grab the component once at the start of the game from within the Enemy script:

Refactoring our GetComponent<>() method

Now your OnTriggerEnter() method should look something like this (nice and tidy!):

Refactoring OnTriggerEnter() method

You should be all good to go! Just to make sure, run your game and watch that your playerLives are decreasing as expected when colliding with an Enemy and that the Player and Enemy get destroyed once the lives are < 1:

playerLives decreasing as Enemy and Player collide

Useful Link:
https://docs.unity3d.com/ScriptReference/Component.GetComponent.html
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter.html

--

--