Is a component/script considered of an interface type if it implements it?

Just a quick question regarding interfaces. In this tutorial, we use a method in Base stats to get any additive modifiers present. We are using a foreach loop and using GetComponents IModifierProvider. Is a component/script considered of an interface type if it implements it? Just asking because most cases I have used GetComponent before is to get the Component that has the matching name/script.matches it.

Yes. If a class implements an interface (or multiple interfaces) it is of that type.

If you have multiple interfaces they will all work, for instance

public interface ITakeDamage
{
    void TakeDamage(int amount);
}
public interface IDealDamage
{
    void DealDamage(ITakeDamage target, int amount);
}
public class Fighter : MonoBehaviour, IDealDamage, ITakeDamage
{
// implementation here
}
public class Test : MonoBehaviour
{
    [SerializeField] Fighter fighter;

    void Start()
    {
        var damageDealer = fighter as IDealDamage;
        var damageTaker = fighter as ITakeDamage;
    }
}

Both damageDealer and damageTaker will be successful.

3 Likes

Thank you for the explanation and example!

An excellent example, and less wordy than some of my explanations. :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms