In the last post, we added the ability to destroy enemies by using Unity’s Rigidbody and Collider physics components. In this post, will introduce a basic health system for the player and damage the player if it collides with the enemy.
Our challenge is to add a lives and damage the player when we collide with enemies. Again, we’re in the prototype stage, so no point in being too precious about how we go about this. It’s more important we keep it as simple as possible for now. Let’s get started.
In our player script, I’ll declare a private int variable named
_lives and initialize it with a value of 3.
private int _lives = 3;
Next, I’ll add a public void method named
Damage that will subtract 1 from our
_lives variable. If we run out of lives, we’ll destroy the player GameObject.
When the player collides with an enemy, we should destroy the enemy and damage the player.
First, make sure the player has a Box Collider with a
Is Trigger checked and a Rigidbody with
Use Gravity unchecked.
In the Enemy script, I’ll navigate to the
OnTriggerEnter method and add a condition to see if the Collider has the
Player tag. If so, I’ll get the player component from the Collider and call the
Damage method on the player.
To test this, I’ll drop three enemy prefabs in the scene and let them hit the Player. On the third hit, the Player will be destroyed!
Our prototype is now becoming what we can consider a game. Although we don’t have enough enemies spawning on screen hit, technically we can attack and be destroyed.
Next up, we’ll introduce more enemies to battle over time.