Nerd For Tech
Published in

Nerd For Tech

Enemy Health System Using Interfaces in Unity

I am working on a third-person survival shooter game. I have the shooting mechanic and the enemy chasing mechanics set up. Now it is time to give the enemies health and make them beatable.

To do this, I created an interface called IDamageable. This will work best because it will be able to work for the player's health system when I set that up. The interface has a Health variable and a Damage method.

Now I added this interface to the enemy and implemented the properties. I set the Health variable equal to the enemy's health variable. I created the Damage method to take away one point of health each time it is called and if health is zero the enemy will be destroyed.

Note: only code related to the interface is shown

Now I had to call the damage function when the enemy is hit. This is done in the shooting script I have set up. When the raycast is sent out I am looking for an enemy tag. If I find one I am getting a reference to that enemy’s interface and calling the damage function.

This gets the enemy health system working.

--

--

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