IDamageable Interface in Unity- Game Dev Series 106
Objective: create an interface in Unity to handle damageable objects.
After setting an attackable sword, now we can try to attack the enemies. The concept of being attacked would be simple. We can create a method like “Damage()” to every enemy object and running the function after collided with sword.
However, imagine that you have tons of enemy object. You would never want to create Damage() one by one. We can create a type called “interface” to make function easier.
Creating an interface
When a class implements an interface, it must have to implement all the methods, properties from that interface. Interface just like a contract, it would force the class that implemented to use all the functions that the interface has.
And a class can implements multiple interface.
Let’s create an interface to handle damage. Create a script called “IDamageable”. To identify the script type, using capital I stand for “interface”, and always using “able” at the end.
Interface could not declare variables, but use a property with getter and setter.
Let’s create an integer property to it.
And create another method to it.
Now we have a property and a method. Let’s implement this interface to an enemy.
Implementing an interface
When implementing an interface, simply add the name of interface after the semicolon of class name.
Once you implement IDamageable, it would show compiler error. That is because you also need to implement all the methods and properties from that interface.
Implementing Health and Damage() as public.
As same as Skeleton, you can implement IDamageable to any class that damageable, like a spider enemy, a box, or even Player.
Calling method from interface
Once we implemented IDamageable to Skeleton, we can test it by using sword to attack.
Open Attack script, call Damage() from IDamageable inside OnTriggerEnter2D().
Then back to Skeleton script and add one line to Damage().
Now we can play our game and try to hit Skeleton to check the result.
It works! We can use this interface to all the damageable objects.