Member-only story

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.

--

--

Valdarix Games
Valdarix Games

Written by Valdarix Games

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

No responses yet