2D Shooter: Communicating Between Scripts Using GetComponent

Sabrina Windsor
3 min readMay 29, 2021

--

When it comes to interacting between different scripts we only have automatic access to the transform component when variables are private. So if one object has a script that tells it to be at a certain position, we can change that position from another script if it collides with an object bearing that script. Otherwise to change anything so easily we would need to be making everything public, and that could potentially be dangerous.

But what do we do if we want to make more complex interactions? Like what if we want the player to get damaged and die after a certain number of hits from an enemy? We’ll be having to create a method that goes beyond positioning, therefor we won’t be able to call it up in another script so easily.

This is where we’ll be using GetComponent.

Now in order for it to work, the method we’re calling up will need to be set to public. But only GetComponent will be able to communicate with it.

Let’s make a Damage method for our player:

This is what will make it so that the player loses a life when it’s hit, and dies if no lives remain. Now in our enemy script, since the enemy has a rigidbody component attached and therefor has a box collider, we’ll be calling up the Damage method within the method that detects collision.

“other” is a variable where the data from whatever object colliding with the enemy is stored. If the data is from the player object, we want to damage it. We do this by making another variable (in this case a player variable), then making the script grab data from the player object by using GetComponent as you see in the image above. Now we have access to the public methods in the player script and we can call the Damage method if contact is made.

Ordinarily, without creating a variable, calling a method using GetComponent looks more like this:

You might be wondering what the transform is doing in this line of code, and that is because the process of interacting with other scripts is hierarchal. The transform component is always first up, and so if we want to get anywhere past it, we have go through transform first.

Current script > Colliding object information (other)> colliding object position (transform) > colliding object script name (Player) > colliding object method (Damage)

Hopefully this helps you understand the concept behind GetComponent!

--

--

Sabrina Windsor
Sabrina Windsor

Written by Sabrina Windsor

Currently learning to code with the help of GamedevHQ in order to someday my my game ideas come to life!

No responses yet