Unity with C# interfaces

Published by

on

Interfaces are a way to make our code reusable.

Example:

public interface IDamageable
{
     void TakeDamage(float amount);
}

public class GoblinBehaviour : MonoBehaviour , IDamageable
{
    float health;
    public void TakeDamage(float amount)
    {
        health-= amount;
    }
}

Now when someone wants to do damage to this GoblinBehaviour they can fetch the component and invoke the TakeDamage method.

Why is this useful?

Couldn’t we just do a GetComponent().TakeDamage(5)?
Yes you could… but then you would be bad…
Let’s entertain the scenario where we want to do an aoe attack.
We want to shoot a rocket then have it explode.
Inside of the explosion volume we want to apply the rockets damage to everything inside.
Like this…

interfaces_explosion

The goblin has a GoblinBehaviour Component but is the Troll a Goblin? I think not.

Doing a GetComponent will only give us the goblins and the troll just goes about his bidness all troll like. Instead what we can do is do a GetComponent() and then invoke our TakeDamage.

Leave a comment