Unity: The Magic of Polymorphism Through Interfaces

Michael Quinn
Unity Coder Corner
Published in
5 min readNov 4, 2022

--

Polymorphism was probably my favorite thing I learned from school. This article will be a brief explanation and example of using interfaces and polymorphism in Unity.

The Definitions

Interfaces

An interface is a concept of abstraction and encapsulation. In C# we can implement interfaces to create “contracts” that require the class that implements the interface to have certain methods.

This sounds crazier than it is. Think of interfaces as clubs and the methods as special handshakes. If you join a club (implement an interface) and that club requires you to know the special handshake, then you will be expected to know that special handshake when someone asks you to perform it.

This is what actually leads to polymorphism.

Polymorphism

Polymorphism is the coolest and hardest concept for me to understand at the time when I was learning it in university, but conceptually it really isn’t that complicated.

If we follow the simile that an interface is a club, polymorphism is the ability to address all the members of that club as the club itself. This means that if you have a class called Tacos, and another class called Burgers, but they both implement an interface called IFood, you can just call each of the classes IFood.

This may make more sense in code when you see it so let’s walk through the above…

--

--

Michael Quinn
Unity Coder Corner

I’m a foodie and a software engineer. Unity and Unreal developer. See more at MikeQ.dev