Interfaces in Unity

Ryan Sweigart
Nerd For Tech
Published in
2 min readAug 4, 2021

--

Objective: Use an interface to damage creatures or objects.

In our game, we’ll want the player to be able to attack not just enemies, but also inanimate objects like crates, barrels, and destructible walls. Now, our sword doesn’t care what it damages, just what it is able to damage. We can use an interface to determine what objects are damageable.

It is standard practice to name interfaces with a capital I as a prefix and able as a suffix. In our case, we’ll call our interface IDamageable. Our interface doesn’t have methods or variables of its own — rather, it tells the object that is going to use the interface what it needs to implement. In our case, we’ll want a Health property and a Damage method that doesn’t take any arguments.

Now we’ll add our IDamageable interface to our Skeleton. We’re not at the point where we’re worrying about points of damage yet, so we won’t do anything with the Health property yet — we just have to implement it to satisfy IDamageable’s requirements. But we will implement the Damage function; the skeleton will tell us when it has been damaged (when its Damage method is called).

Now we’ll look at the player’s sword’s Attack script. in its OnTriggerEnter method, if the other object it collided with has an IDamageable component, it will call that object’s Damage method. This is safe to do because we know anything using the IDamageable interface has to have a Damage method!

We can see by the output the skeleton has been damaged!

--

--