Communication using GetComponent

Valdarix Games
3 min readApr 12, 2021
Photo by Ben Wicks on Unsplash

We often need our scripts to able to communicate with one another. In my article on Variables I discussed how we can use public variables to accomplish this. However, as mentioned in that article it isn’t desirable to allow variables to be changed directly by another script. It is better if we use private variables and use methods to access and update them.

In our space shooter game we have given our Player a variable that will hold the number of lives the player has left and created a method to apply damage to the player that will reduce the number of lives remaining.

Apply damage method

So we have a way to damage the player but how do we actually utilize it? Do we add a collision detection on the player and damage it when the colliding object is the enemy? We could but that might get cumbersome and scale poorly if we add a bunch of different types of enemies to our game.

Instead, we will allow the enemy to notify the player that it has been damaged. This way we can use our enemy class to represent all of our enemies. Inside of our Enemy class we add a variable for damage amount so we can adjust damage values based on the strength of the enemy.

So our default enemy can only do 1 damage, however since we serialized it we can adjust different enemies to have different values in the inspector.

GetComponent in action

Now inside of our collision detection we assign a variable of player to type Player and give it a value of the Player component using GetComponent<>. What we are actually getting access to is the Player script component on the Player transform object. If the script was named PlayerScript instead of player we would use that in the <> of GetComponent to communicate with the script. Now we can access any method or variable that we have declared as public in the Player script. We currently only have DamagePlayer() which we are passing _damageValue which you can see above is one. So we can quickly apply 1 point of damage to the player when the two collide.

Using this method allows us to access the players DamagePlayer() method from any other object script in our game. So not only can we have the collision cause damage but we can have the enemies shoot to cause damage, or crashes into rocks cause damage, etc.

We also can access other components on the other.Transform to modify any other component in the inspector.

One step close to moving from prototype to actual game.

--

--

Valdarix Games

Turning my passion for video games and software development experience into a focus on video game development.