Unity Abstract Class

In by John FrenchPublished Updated

An abstract class in Unity is a class that must be implemented by another class that is inheriting from it.

For example, an abstract class can’t be used as an instance, you’ll need to create a script that inherits from that abstract type and then use that instead.

Like this:

public class AbstractExample : BaseClass
{
    // This can be added to an object
    private void Start()
    {
        BaseFunction();
    }
}

public abstract class BaseClass : MonoBehaviour
{
    // This can't be added to an object
    public float number;

    public void BaseFunction()
    {

    }
}

This can be useful when you want to create multiple different types of a thing, but without using the base type directly.

Abstract Functions work in a similar way to abstract classes.

They force an inheriting class to implement a version of the method they’re overriding that has the same name and argument pattern as the original.

Like this:

public abstract class Shape : MonoBehaviour
{
    public abstract void CountSides();
}

Because the original function is abstract, and can’t be called directly, it doesn’t need to have its own body.

Likewise, because it contains an abstract function, the class itself must also be abstract, meaning that you must create a derived class in order to use it.

The benefit of this, however, is that you can define any type of object, such as a Shape, without knowing what the shape is going to be, and pass any class that inherits from it as an argument in a function or as a reference in a variable, and it will just work. This is polymorphism which is a cornerstone of OOP and Inheritance in Unity.