2D Galaxy Shooter — Lives System using “GetComponent”

Marcus Cohee
3 min readAug 12, 2021

--

Hello all!

Today, I will go over how to make a lives system for our player using “GetComponent”. Let’s get into it!

Creating the Lives Variable and Damage Method

  1. Go to the Player script.
  2. Create a variable — [SerializeField] private int _lives = 3;
  3. Now create a new method that is public called,
    public void Damage()
    - making it public will allow different scripts to access it using GetComponent.
Damage Method for Player

Looking above, when Damage is called, you will subtract one life and when your lives reach less than 1, you die.

Using GetComponent to reference Damage()

  1. Let’s head to the Enemy script and head to the OnTriggerEnter method.
  2. There, let’s make a new if statement.
if statement for damaging the player

This is saying that when “other” = Player, then call the damage method we just added on the player script, and destroy the enemy.

The only thing we have direct access to is the transform of a GameObject, so we can’t just ask for the Player script by saying, other.Player. It will fail.
By using GetComponent, we can call other components, like mesh renderer or scripts, which we need here.

  • A small note, a GameObject is a transform, and a transform is a GameObject. This will help me explain.

So looking at the code above, other = player, so we want to look into its transform, then get the script component called Player, then call the Damage() method from there.

Best Practices: Null Checking

using a null check

Looking above at the new layout, I made a variable called “player” to get the Player script component. By doing it this way, I can null check to see if the Player script can be found. If the Player script is where I said it would be, then it will run the Damage method. However, if we ran it without a null check and the script was gone, it would cause a hard crash and we don’t want that for our end users.

By doing it this way, it will allow me to null check, which means that if there’s a bug in my game and the Player script can’t be found, it won’t break my game. Bugs are still an issue but at least the end user won’t be dealing with hard crashes.

Remember, it’s best practice to null check when using GetComponent.

Player lives demo

Now we have a lives system!

Next, let’s make a SpawnManager to get more enemies in our game!

Thank you for your time!

--

--

Marcus Cohee
Marcus Cohee

Written by Marcus Cohee

I am starting Unity and learning the ropes as I go! Let’s take this journey together!

No responses yet