Using interfaces for TakeDamage
In a previous article ( Use abstract class or interface ) I wrote about interfaces, but I think the example was not clear enough.
First, we need to think about how many game objects in our game will receive damage. Let’s say 3 objects
Now, when the Laser executes OnTriggerEnter
, will apply damage to the other
game object. The code will look some like this:
You got to check the tag in other
and also if the other
class ( Box Ball Kite
) is not null
Here we have some points to take on account:
- If you change the name of any class, you will need to refactor it, and it’s not just about ‘rename’ it.
- The code works fine for 1, 2 or 3 game objects, but in video games the reality is we can find hundreds of game objects that can execute
TakeDamage
, so the developer would be forced to write hundreds ofelse if
statements
Here is where we apply the Interface pattern
Interface pattern:
- When a class inherits an interface, the class must implement all of the interface’s methods. That is called ‘contract’
- Each class is free to implement the interface’s methods as desired
Let’s declare the interface
Let’s implement it in all classes
Now we will see why the interfaces are so important
With this code snippet, the Laser will apply TakeDamage
to the other
game object.
Laser doesn’t care about the other
tag, or if the class name is Box
Ball
Kite
or any other one, the only thing that matters for Laser is if other
inherits from ITakeDamage
.
If so, it will execute the method implementation of ITakeDamage
in other
( in this case it will be Box
), which is private void TakeDamage(int damage)