Player Lives and Damaging Systems in Unity!

Damage() method in Player Script

First, let’s create a variable ‘_lives’ with the value of 3 in the player script.

  1. lose 1 life each time when this method is being called.
  2. Create an if statement — if lives reach 0 (or less), we will destroy the player.

GetComponent<>

In Enemy script, we previously created OnTriggerEnter () method that will destroy the player instantly.

  • GetComponent<> will find a specific component that is attached to the game object called in <>. In our case, we are looking for a script component called, ‘Player’, then look for Damage() method within that script.

Null Checking

It may appear that we are all done, but there is one last thing that we should do — Null Checking.

  • create a variable called ‘player’ that will store the player component.
  • create an if statement: if the variable ‘player’ is NOT null (null = zero or nothing). In short, if the Player component is found, call the Damage() method.

--

--

XR Unity Developer / Designer / Architect

Love podcasts or audiobooks? Learn on the go with our new app.

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
Du Young Yoon

Du Young Yoon

XR Unity Developer / Designer / Architect