Abstract classes and inheritance in Unity & C#

Objective: Quick overview of an abstract class and inheritance

Like with our parents we inherit some of their genetic traits. In object orientated programming the concept is similar.

You have a base class, in my case called Enemy and I have child classes that inherit from them and have the same attributes.

In my case, my enemies will all have attributes called, health, speed, gems and two transform points. These will be needed for all child classes.

If you make the attributes private, then no one, including the child classes are allowed access to them. You could make them public, but then any class can get access to them. There is a third option for child classes which is protected.

I have serialized the fields, so that I can adjust them inside the editor in Unity.

You can see that I don’t have the enemy script attached to the MossGiant, I just have the MossGiant script. The reason that the fields are appearing here is because the MossGiant class is inheriting the fields from the Enemy class.

MossGiant class inheriting from Enemy

I have made my Enemy class abstract because it will incomplete and will have functions that each enemy needs.

When creating methods inside of an abstract class that you want the child classes to implement you can have the abstract word in front of the method name and with no body.

This means that the child class must have an implementation of this method or you will get errors when compliling.

If you do not have the method implemented you can automatically implement them by using the quick refactoring option see above. You can also create methods in the base class(parent) and override them in the derived(child) classes. You set them up by using the virtual keyword.

These methods don’t need to be implemented in the derived class but can be used by overriding.

Integration support and part-time game developer