Implementing a lives system using GetComponent in Unity.

Objective: Learning how to create and remove lives using GetComponent in Unity.

When you create a variable in a script, it is solely in that script. You can create the same variable in another script and set it to a different int, string, bool, or float, and it won’t conflict with the other. Say I have an enemy script, and I want it to remove a life from my player. Let’s look at how to do that.

First, I need to create a private int variable in my player script dictating the number of lives your player has. Let’s say the player has three lives.

Next, we have to create a method called “Damage”. Create “public void Damage()” and now let’s define it. Let’s take our current lives and every time it’s called, let’s subtract one.

(There are a few ways to right subtract one, for this instance we could do

_lives--;

_lives = _lives — 1;

_lives -= 1;

They all do the same thing.)

Next we need to check if we have no lives remaining. Create an if() statement that asks if lives are less than one, then destroy your player.

The next thing and the most difficult part of this, is going to getting the enemy to call this method using script communication. In our player script, we need to get another component of a different object. The only thing everything has direct access to is the transform of another object. So how do we do this? We use Get.Component.

Type “other.transform.GetComponent”

The component that we are trying to get is the “Player” component.

Continue the line of code.

“other.transform.GetComponent<Player>().Damage();”

In our current script it would look something like this.

The component you get can be any component that a game object has. It could be the rigidbody, mesh renderer, box collider, etc.

Now if you start your game, and get hit 3 times, your player will get destroyed!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store