Polymorphism

In by John FrenchPublished Updated

Polymorphism is a feature of Inheritance, and is the use of a single interface to represent many possible different types.

In Unity, a common use of polymorphism is Subtyping which involves allowing a derived class to be used where a base class is expected.

You’ll find examples of subtyping in many of Unity’s own functions and features.

For example, there are many different types of Collider, such as box colliders and sphere colliders) that each work in a slightly different way.

But, fundamentally, they all inherit from the Collider base class, meaning that physics functions can use and return any type of collider that they interact with, so long as it inherits from the same base class.

This can be extremely useful when you want to use a type of something, but you don’t necessarily know what it will be.