Virtual Methods For Dummies

In a previous tutorial, we take a look at Custom Classes and Inheritance.

Now we will take a look at Virtual Methods within Unity. For the purposes of this example, we have a script named Pet that will inherit from Monobehavior.

Say we have a game object named Duck with a Duck script on it that inherits from Pet (which inherits from Monobehavior).

The Duck script would have access to the Speak method declared in the Pet script. HOWEVER, ducks don’t say, “Speak!”. They say, “Quack!”. So, how do we override the original method?

We can make the Speak method a protected virtual method. Protected means that the variable or method is private and inaccessible to other scripts but accessible to the initial script and all that inherit from it.

Learn More