Virtual Methods and Overriding

Objective: Override parent Class methods with a child’s method.

Natalia DaLomba
Women in Technology
2 min readJul 3, 2023

--

In C#, we can inherit from MonoBehaviour Classes. Imagine we’re creating a pet system in our game. Let’s start by creating a Pet Class.

using UnityEngine;

public class Pet : MonoBehaviour {

//the new keyword is used because Unity has an internal variable also
//called name so we're overriding it to be our own in this instance
public new string name;

public void Speak() {
Debug.Log("Speaking!");
}
}

To run and test our game, we have a short PetGame script and set up our Scene:

using UnityEngine;

public class PetGame : MonoBehaviour {

[SerializeField] private Pet pet;

void Start() {
pet.Speak();
}
}

When we press Play, our Duck says “Speaking!” instead of what would make more sense, like “Quack!”. To solve this, we can create a Duck class that inherits Pet. In Pet, we will need to allow children Classes to be able to override the Speak method by declaring Speak as a virtual method. virtual allows us to override from any Class that inherits Pet.

using UnityEngine;

public class Pet : MonoBehaviour {

public new string name;

public virtual void Speak() {
Debug.Log("Speaking!");
}
}

Then in Duck, we can override the Speak method like so using override:


using UnityEngine;

public class Duck : Pet {

public override void Speak() {
Debug.Log("Quack!");
}
}

Keep in mind, the children and parent’s variables/methods both have to be stated as the same access modifier. So the Speak method in both Classes need to be public in our case.

--

--

Natalia DaLomba
Women in Technology

A Unity C# developer inspired by game design logic used to create digital adventures. https://www.starforce.games/devlog/