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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Data Scientist Programming Syllabus Complete Road Map Part 2

Linux command cheat sheet — by IORI

Highly available kubernetes controller plane

Taxa Monthly Highlights for July 2020

How to host your static websites on GitHub with https for free

Secure and sane setup of new virtual instance on any cloud provider

How to Implement Row Level Security in Power BI

Artisan command laravel

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
Kyle W. Powers

Kyle W. Powers

Unity Developer, Software Engineer, Game Developer

More from Medium

Pipeline Checklist- HDRP (wip)

How to get GIT Bash for Unity

Journal 146 — Unity Project Development, 2.5D Shooter

Damage VFX using Animated Sprites in Unity