Enemy Set Up — Damage Using an Interface

This article will show how to use an interface to allow the Player to damage and destroy an Enemy. An interface is a script that requires that methods and properties outlined in the interface be implemented when inherited by a class.

To have the Enemy show that it has been attacked, we add a Trigger for Hit and set the hit animation to play from any state and then transition to idle.

To create an interface, you use the interface keyword. An interface is often named with a prefix of “I” and a suffix of “able” to distinguish it from other scripts. The IDamageable interface will force the inheriting scripts to have an int Health property and Damage method.

To add an interface to a script, we add it after the inherited class with a comma separating them. Then we implement the Health property and set it to the health variable from Enemy.

Next, we implement the Damage method. The method decrements Health, triggers the hit animation to play, checks if Health has reached 0, and then destroys the Enemy.

In the Attack script, we can now check the GameObject collided with for the IDamageable interface and call the Damage method. Since we are using an interface, we do not need to call a different method for each GameObject based on the attached script.

When the Player’s attack hits the Enemy, the hit animation plays and then transitions to idle. The only problem is the Enemy continues to move during the hit animation. We will fix this in the following article when we give it the ability to attack.

Unity Developer, Software Engineer, Game Developer