Helps us write cleaner reusable code that lets up define code to be reused and decouple code.
The interface works as a contract. Which means if a class is subscribed to that interface they must implement those functions. We don’t define an accessor or implimentation. Everything is public in an interface by default.
1
2
3
4
publicinterfaceIMyInterface{voidTestFunction();}
! In C# 8 you can actually define a default implementation for functions in an interface.
publicclassTesting:MonoBehaviour{privatevoidTestInterface(IMyInterfacemyInterface){// expects an IMyInterface object, anything that implements the interface can go heremyInterface.TestFunction();//}privatevoidStart(){MyClassmyClass=newMyClass();TestInterface(myClass);// once we've instanciated the class we can use the testinterface function because the class implements the interface}}publicclassMyClass:IMyInterface{publicvoidTestFunction(){Debug.Log("MyClass.TestFunction()");}}publicinterfaceIMyInterface{voidTestFunction();}
one of the useful things with interfaces is that you can implement more than one. With inheritance you can only inherit one parent.
Structs cannot inherit from a baseclass but they can implement interfaces.