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

A Successful Hard Fork, State Channel Improvements and Expanded Node APIs

Pause to Reflect…

4 Handy Git Commands for Fixing Common Code Base Problems

Git branches

Integrating IATI — a tech overview

Google Summer of Code 2018 with OpenStreetMap [Phase- 2]

Amazing PandasGUI: Analyze Pandas dataframes with a Graphical User Interface

14 language features in TypeScript and Dart you may miss in Java

Cypress and GraphQL

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

Creating MineField In Unity (Part 2)

Drawing rectangles

2.5D Phase1 Framework: Moving Platforms

Unity and Variables❤