Step 4 — Script to Script Communication with GetComponent

Nicholas Lim
2 min readApr 6, 2021

--

Video games are all about things interacting with other things, then changing the state of the things involved.

Take the below example again, of an “enemy” colliding with the “player” and destroying them. In this case we want our player, who has a variable keeping track of lives left, to minus one life. The enemy will be the one to tell the player to do that.

To begin, add Colliders to both objects, and tick the IsTrigger toggle on the enemy Collider. Then add a Rigidbody on the enemy. Make sure the Rigidbody has no gravity acting on it.

Next, as the collision will be of Trigger type, add a OnTriggerEnter method to the Enemy script.

The Collider argument is referring to the other object that *this* object is colliding with, so in our scenario other is the Player object.

First things first, check the tag of the object I’m colliding with. Tags are a great way to organize game objects, and can be set in the Inspector. The player object can be tagged as “Player”.

Next, we create a variable of data type Player script, and populate this variable by accessing the Player script from the other object by using the GetComponent<Player>() method.

If that method doesn’t return as null, then call the Damage() method on the Player’s script, and finally destroy this enemy object as it has completed its job.

Hop on to the Player script next and add the following:

This is the method that the Enemy object was calling. Remember to make this public so that the Enemy can see and call this. The method will decrease lives each time it is called, and if it falls to zero the player has died, so destroy the object.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response