Creating an IDamagable Interface in Unity

Interfaces are a great way to modularize or decouple your code. If you look up the definition of an interface, you will likely be greeted with some form of this text:

“An interface is a contract between an object and it’s user…”

So what does this mean? Essentially, an interface is just a collection of method and property declarations that must exist within any class that implements the interface. For example, if an interface has a Health property and is implemented by a Player class, the player class must also have the Health property.

In order to create an interface, we create a new script and change it from a class to an interface:

With the interface created, we can now add any methods, properties, events, indexers that we need. In this example, we’ll add a Health property as well as an Attack() method:

Let’s create an Enemy class that will implement this interface:

In the above example, our Zombie class is inheriting from Enemy and implementing IDamageable. Classes in C# can only inherit from a single class (one parent) but can implement many interfaces.

By implementing IDamageable, we are guaranteeing that our Zombie class will have everything that the interface being implemented will have. Now instead of referencing the specific enemy type or even the Enemy class, we can simply create an instance of IDamageable and we will have access to any class that implements IDamageable:

We can now implement this interface in anything that needs to take damage…from a crate, to an enemy, to a vehicle! This is the power of interfaces!




Unity Developer

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

Recommended from Medium

What is __name__ == “__main__” in Python?

DigiFinex AMA Recap | How is Akash Network building the future of the cloud?

How to Remove Software Installed From Source Code in WSL2

Goodbye Grails, Hello Micronaut #6: Domain Classes

Running a Firefox GUI in a Docker

How To Use Custom Domain With AWS Lambda And Serverless

Top 10 Serverless Monitoring Tools in 2020

The Benefits of Hiring A Full Stack Developer For MVP Development

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
Mike Brisson

Mike Brisson

Unity Developer

More from Medium

Unity and Cinemachine — Virtual Camera Aim Options

Working with Screen Space Reflections in Unity’s HDRP

How to Install the Universal Render Pipeline

Working with Cinemachine & Timelines