Day 23: Setting up our attack system with an Interface for taking damage

Philip Johnson
3 min readAug 4, 2021

Objective: To build more on top of our combat system and modularize our code even further for re-usability and diversity. We will add the implementation of an interface to Damage any object that can receive damage.

So now that we have the base of our enemy class we can deal with enemy objects specifically and modularize the code for re-use and versatility. Before writing this article I went ahead and created movement code that is shared by all enemy objects, but because the base class uses an override method, the child class can choose implement the shared movement code or not.

I added more variables to the parent Enemy class that is shared and implemented among all Enemy types.
The new movement logic that is implemented into the parent enemy class

For the health variable, well set its value inside of the child classes that inherit enemy. To set the health we use a property in our child class.

The IDamageable keyword in the top right of the GiantRat child class represents an interface I wrote that will be shared by all objects that can receive damage.

We use this interface to cause damage to any object that inherits from it. An interface will require the inheriting objects to implement the method Damage(). In an interface we simply declare a function. We do not write the implementation inside the function within the IDamageable script. As mentioned in the previous paragraph, we use an auto property to set the health within the child classes.

The child class will implement the class declared inside of the interface we just created. The inheriting class will fill this function with code that makes it unique to the object the child script is attached to. Now that we have this set in place we need to use it when we swing a sword. I added a box collider child to the player model that we will animate to act as a hit box. this box has the Attack script attached to it. The attack script will search for anything it collides with and check for IDamageable functionality.

This box collider is a hit box that will turn on and off with our animations

Now that we have this we will need to update our animator for our enemies.

We also need to make sure that our enemies have capsule colliders attached that are set to triggers. We also need to deal with layer masks so that our sword only attacks objects on a layer that our sword will recognize. I wont go into detail about how to set every layer in unity. After you set the layers the way you like it we will end up with a nice start to a combat system that relies on modular code to function effectively.

+

The effect can be seen in the gif at the top of this article.

--

--