What exactly is the point of Interfaces?

I read the Unity Learn section on it, but I’m still a bit confused. Are they to classes what scriptable objects are?

An interface is simply a contract. It guarantees that the class implementing the interface will have all of the methods that are defined in the interface.

Our interface, for this section is IAction
The IAction interface looks like this:

public interface IAction
{
    void Cancel();
}

Now any class that implements the IAction interface MUST have a public Cancel() method. Our two classes that will be implementing IAction are Mover and Fighter, this means that both Mover and Fighter MUST implement an Cancel() method. What they have in that method is unimportant as far as the interface is concerned. They simply must have that method.

This allows us to reference a class by it’s interface instead of by it’s given class name… so if I have an

IAction currentAction;

I know that I can call

currentAction.Cancel();

on the currentAction, assuming that it is not null. I don’t need to know if the currentAction is a Mover or a Fighter, or any other class I might have implement IAction. All I know is that this is an IAction, and that because of this, I can call Cancel() on this IAction and I know that the code will run.

1 Like

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

Privacy & Terms