Abstract Classes in Unity — part 3, the Interface bits.
An abstract class pulls double duty both as a Monobehaviour, and as an interface, the difference between an abstract and an interface class is an abstract class can contain variables and code and actually run them, whereas an interface is only a template that forces another sub-class to conform to its template.
Interfaces are useful if you want to refer to various objects by a common attribute, like in our case, we have enemy objects and random items that can be broken so we can have a damagable interface or abstract class.
As an example, all of our enemies will walk towards waypoints and MUST have an update method for that to happen. While we can use a virtual Update in our enemy class, it’s optional for the monster sub-classes to use it, which may be unnacceptable. We will force every sub-class to use an update!
First, you need to specify that the class is abstract:
Next, create a public method you want to make obligatory putting ‘abstract’ before the method type:
notice there are no brackets and you end it normally with a semicolon.
Normally, Mono or Code would tell you there’s an error but you can always count on Unitys console to let you know there’s a problem:
It’s telling us that we MUST implement an Update method, (and not just a regular one, but an override) so let’s do that now.
And Unity no longer has any problems!
These are really fascinating methods to be using in Unity programming, I’ll be sharing what I discover in the coming days!