Script Communication in Unity using GetComponent

Micha Davis
3 min readApr 7, 2021
A person speaking into an aluminum can on a string.
Wrong number.

So far we’ve learned that methods can be “Public” or “Private,” and that a Public method can be called by any script in the game. But how does a script component on one object access a script component on another object? That’s where OnTriggerEnter and GetComponent come in.

We’ll go back to our space shooter prototype as an example. Right now we can fly, shoot, and enemies can fall from the top of the screen, but that’s about it. We need to take the collision data we engineered in the Intro to Physics article and use it to resolve each collision appropriately. Specifically, we need to destroy enemies & lasers, and damage the player.

First, I’ll open up my Enemy script and drop the following pseudo code:

OnTriggerEnter detects whether a collision is triggered between this object’s Collider and the “other” object’s Collider. What I want to do is find out who “other” is and then program the appropriate response.

One way to do this is through the Tag property of game objects.

I’ve created three new tags: Player, Enemy and Laser. I’ll assign these tags to their respective objects. Then it’s back to the Player script, where I will create a public method for damaging the player:

Since the collisions with incoming enemies and laser fire will be detected by other scripts, our Damage method will be public. Next we’ll slide over to the Enemy script and work out the code for telling who hit whom, and what to do about it.

So, the final chain of events looks like this: When the enemy collider touches another collider, if that other object has a Player tag we access the Player script via GetComponent, if the component exists we run the Damage method, and finally we destroy the enemy. Or, if the other object has a Laser tag (heh) then we destroy the laser and the enemy both.

That’s all it takes to get simple collision detection and consequence going. Let’s watch it in action:

Not bad! I’d say this technically qualifies as a game, now.

In the next article I’ll construct a Spawn Manager and we’ll use that occasion to learn about coroutines in Unity.

--

--

Micha Davis

Unity Developer / Game Developer / Artist / Problem Solver