2D Galaxy Shooter — Lives System using “GetComponent”
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
- Go to the Player script.
- Create a variable — [SerializeField] private int _lives = 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.
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()
- Let’s head to the Enemy script and head to the OnTriggerEnter method.
- There, let’s make a new if statement.
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
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.
Now we have a lives system!
Next, let’s make a SpawnManager to get more enemies in our game!
Thank you for your time!