My journey becoming a Unity game developer: Player lose lives prototype for Galaxy Invaders

Rhett Haynes
3 min readJun 16, 2022

--

Objective: Setup Player to lose lives and be destroyed after running out of lives when hit by the Enemy.

Player receiving damage by losing a life after each collision.

We want our Player to receive damage when being hit by the Enemy. This will be a simple setup where the Player will lose a life every time the Enemy collides with them. The Player will be given 3 maximum lives to start the game off with, and when they run out the Player will be destroyed signaling game over.

Let’s begin in the PlayerBehavior script by creating a new Private Float variable with a SerializeField attribute name _lives which will have a 3 as its default value.

Next, we will create a method to handle the Player receiving damage and losing lives every time they’re hit. We will name this method Damage() which will subtract 1 from the _lives variable after every hit.

We also want to check IF the Player’s _lives is less than 1 which will make it zero. If it’s true, Destroy() this Player’s game object to effectively end this game.

Damage() method created to take lives away from the player when they’re hit.

Back in the EnemyBehavior script inside the OnTriggerEnter() method, IF the other object colliding with the Enemy is the Player’s Tag, we will get the transform of the Player and Get the PlayerBehavior script Component. Then use the Damage() method officially give damage to the Player when colliding with the Enemy objects.

Gaining access to the PlayerBehavior’s script through the GetComponent function.

Playing the game we see the Player losing lives in the Inspector under the PlayerBehavior script component.

Player loses lives after each collision, and is destroyed when they run out of lives.

To use better code practice, we will 1st create a new variable inside the OnTriggerEnter() method. The Type is PlayerBehavior and the name of the variable is player. Set the value to get the PlayerBehavior component of the other transform.

Second thing we will do is NULL check to see if the PlayerBehavior script is active. IF the player isn’t equal to NULL, call the Damage() method through the player variable to give the Player damage. Then, we want to Destroy() this Enemy game object after its collision.

NULL check the PlayerBehavior component before damaging the Player and destroying the Enemy.

The game is playing with the Player active, therefore signaling that the PlayerBehavior script is active. We can also use the Damage() method before destroying this Enemy object.

Player receiving damage after passing a NULL check.

--

--

Rhett Haynes
Rhett Haynes

Written by Rhett Haynes

Learning to become a Unity game developer.

No responses yet