Script Communication with GetComponent: GameDev Journey 04

Using GetComponent to communicate between scripts was something that I was familiar with, but now I understand it much better. In my current Space Shooter game, I needed to use GetComponent on my Enemy script to communicate with my Player script so the player loses a life when it hits an enemy. To show you how I did this, I will take a snippet of my code then explain my way through it.

The first thing I did was make a variable. Any component on a game object can be a variable type. In this case, the component I want is the Player script so Player is the variable type.

The next step is to assign this variable in the start method. The_player variable was assigned to:

GameObject.Find(“Player”) .GetComponent<Player>()

GameObject.Find() finds the specified object in the scene, in this case is was the Player game object. Now I could use GetComponent to access any component on this Player game object. Since I want to communicate with the Player script, and that's what my variable type of_player is, GetComponent<Player>() is what I used.

The if statement that follows is a null check. If for some reason the component isn’t assigned to _player this will give me a message in the console. This is important because null references can cause many issues when creating a game. You should null check when you communicate between scripts and use GetComponent most of the time. Now that the Player script is assigned to _player, we can access the Player Script’s public methods like this :

This snippet of code makes the player lose a life when it collides with an enemy. _player.LoseLife() calls the public method LoseLife() inside the Player which looks like this:

This subtracts 1 life from the life total , and destroys the player once their is no more lives. You can see I also am communicating with the SpawnManager script as well using the same method I just went over, but on the Player Script.

Hope this helps and I will see you soon in my next post!