Getting a Clue with GetComponent — Script Communication in Unity.

Jack Leavey
3 min readMay 24, 2022

--

It is vital that the various scripts in a videogame can interact with one another to create the desired behavior. In this example, I will show how to call a “damage” function on the player character from a script attached to the enemy.

First off, let’s write out the logic on the player script. I want my player to have 3 lives, and when the last life is gone (playerlives = 0), I want the player to be destroyed.

First off let’s make a new int variable called currentLives. I default mine to 3.

Next, what do we want to happen when the player gets hit by an enemy?

We want to increment lives down by 1.

So we make a new method called PlayerDamage.

Whenever this method is called, I want to subtract 1 from my currentLives integer variable.

Two minus signs will increment down 1.

Finally, “if” my lives is 0 (or somehow less), I want to destroy my player. It’s a simple “if” statement!

So now that the logic is implemented, how and when do we access it? We want this logic to run when the player collides with an enemy. So we want to call this method from the Enemy.cs script in the OnTriggerEnter method.

First, we need the Enemy to understand what the player is, so create a variable to hold the player.

Next, in Void Start we want to assign what the player is. We cannot set it in the inspector as we will be prefabbing our enemy, and thus any tracked references must be set when they are instantiated.

You can assign tags in the Inspector, at the top left of the window when you have an object selected.

This is where we can use “GetComponent” to run the method from another script.

Pay close attention to grouping symbols when using GetComponent!

Notice how we can call any public function when using GetComponent. You can also call any public variable from another script as well!

So now when we collide with an enemy, we lose a life. And if we go below 1 life, we are destroyed!

--

--

Jack Leavey
Jack Leavey

Written by Jack Leavey

I am a software engineer with years of experience branching into game development, specifically in Unity. Follow along for guides on creating game mechanics!

No responses yet