The Magic of Interfaces to bring the PAIN.

At this point, I need to create a damage system for my enemies. However what if I have more than one type of enemy? What about if I want other objects to be damaged? I don’t want to make a new damage script for every separate object or enemy so it is time to learn about interfaces.

An interface is like a contract, and if the object that has it applied, it must have the required items from the interface.

To begin, we create a script called IDamageable (Starting with a capital I to denote it being an interface) and instead of inheriting from monobehavior, we do as in the image. “public interface IDamageable”.

We then can add our first requirements. An auto property for Health, and a Damage method.

By adding the IDamageable interface to my Skeleton script as above…

like a contract, this script must now have both the Health property as well as a Damage method, or else the script will error.

So what actually makes this special? Well…

In my attack script, I can actually check for the IDamageable interface in and enemy or object using a GetComponent. So when my sword attack enters a collider, it will attempt to get the IDamageable component and store it in “hit”. If it isn’t null, it will actually call the function in whatever the object was!

Previously I had mainly used tags to denote what triggers what, however with more and more enemies in a game that can be quite the hassle. With the interface, my attack doesn’t know if it hit a object, or a enemy, but all that matters is that the object has IDamageable and the hit will be registered!

C# never ceases to amaze me in what it can do and I hope it never stops.

See you next post!

--

--

--

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

Recommended from Medium

Loading Scenes in Unity

A Guide to OAuth2.0 Authorization with Django Rest Framework.

Data Structures Part 1: Essentials

SMALL WRLD: The Journey Begins

The Algorithmic Approach in Life

Header image of the blog

Integrating AWS Secret Manager with EKS and use Secrets inside the Pods: Part-1

The Evolution of Large-Scale Co-Location Technology at Alibaba

Checklists before connecting to Redshift from your Local Computer

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
Edward Kim

Edward Kim

More from Medium

Lerp Squares — Part 2

‘Dodge The Spike’-Endless Runner Tech Blog

2.5D Platformer: Moving Platforms

Prefabs in Level Design