Polymorphism in Unity

ยท 1 min read
Polymorphism in Unity
Polymorphism in Unity

Like many other programming languages, Polymorphism is a feature of object-oriented programming that allows classes to have more than one type. Simply put, we can let a child class considered as its parent class type. This is especially useful when dealing with common functionality among different classes.

For example, let's say you have a list of game objects of different types, such as beast, enemy. With polymorphism, you can group these game objects under its parent class type and the same code can be used to handle all objects in the list. It also allows you to access common methods and properties of the parent class from the child class. For example, both beast and enemy can attack, walk or die.

Example of polymorphism

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LivingObject : MonoBehaviour
{
    public void attack(Collider other) {
    	// attack code
    }
    
    public void walk() {
    	// walk code
    }
    
    public void die() {
    	// die code
    }
}

public class Dragon : LivingObject
{
}

public class Robber : LivingObject
{
}

As in the above example, any class inherited from LivingObject, either Dragon or Robber can walk, attack and die.