My journey becoming a Unity game developer: Player lose lives prototype for Galaxy Invaders
Objective: Setup Player to lose lives and be destroyed after running out of lives when hit by the Enemy.
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.
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.
Playing the game we see the Player losing lives in the Inspector under the PlayerBehavior script component.
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.
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.