Nerd For Tech
Published in

Nerd For Tech

Adding a Health System to the Player

In order for the Player to be damaged by an Asteroid we have to set up the logic for taking damage and losing health. However we’d like to use this method for other cases and preferably each time with a different value, such as when we fly into an actual Enemy, or we get shot by one. We can do that by exposing a variable in the method name, let’s have a look.


Adding a Health System for the Player and adding a Method to Damage the Player in a modular fashion so we can re-use it.

Case Solution:

Adding a method with an exposed variable responsible for subtracting Health Points.


First we have to add two Integer variables in the Players.cs Script. One for our Current Health and one for our Maximum Health.

In addition, add a bool variable that will return true or false for Infinite Health.

In the Inspector we can specify the Maximum Health. I’ve set it to 100.

Then at start we simply say that Current Health is equal to Maximum Health. Believe it or not, it’s just that for adding our Health System to the Player. If you’d press Play you can see that the Player now has 100 Health.

Except, we would like to have a way to subtract Health Points from our Current Health. For our convenience we create an extra method that allows us to Enable/Disable Infinite Health in the Inspector.
We declare that if Infinite Health is set to false, we subtract the amount of Damage Points we pass in from our Current Health and if Current Health is less than 1, we destroy the Player. Otherwise Current Health is set to Maximum Health.

Going back to the Asteroid.cs Script now all we have to do is pass in a damage amount in the OnTriggerEnter Event. You can cache it in a member variable for easy adjustments later.

We can look at the Players Health in the Inspector in Play mode for now, we’ll soon have a look at adding User Interface elements to make it visible for the Player as well.

Good luck setting up your own Health system!

Previous | Next



NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit

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