Classes in Unity (Part 3/3): Protected Data Members and Virtual Methods
In the previous blog post, we talked about Class Inheritance and created a simple example featuring common items in a video game. In today’s blog post, let’s talk about protected data members and virtual methods in Unity.
Protected Data Members
Currently, all variables we have in the Item script are public, meaning that any class can access and change them.
public class Item
{
public string name;
public int id;
public string description;
public Sprite icon;
}
In order to only allow inherited members to access this data, we can declare these variables as protected instead of public.
public class Item
{
protected string name;
protected int id;
protected string description;
protected Sprite icon;
}
Also, we can do the same for methods:
public class Item
{
protected void EquipItem()
{
Debug.Log("This item has been equiped");
}
}
Virtual Methods
Virtual methods in Unity allow functions in inherited classes to be overridden. To demonstrate this, I’m going to create a simple script called “Pet” with a variable for a pet’s name and a method for a pet to speak.
public class Pet : MonoBehaviour
{
protected string petName;
protected void Speak()
{
Debug.Log("Speak");
}
private void Start()
{
Speak();
}
}
Next, I’m going to create two pets: a dog and a cat; and each has its own script that inherits from the Pet class.
Since I want the Dog to say “Woof” and the cat to say “Meow” instead of “Speak”, I’d need to turn the Speak method into a virtual method to override it in inherited classes. To do that, I’d add the “virtual” keyword before the void one.
public class Pet : MonoBehaviour
{
protected string petName;
protected virtual void Speak()
{
Debug.Log("Speak");
}
private void Start()
{
Speak();
}
}
Also, in the Dog and Cat script, I need to override the Speak method.
public class Dog : Pet
{
protected override void Speak()
{
Debug.Log("Woof!");
}
}
public class Cat : Pet
{
protected override void Speak()
{
Debug.Log("Meow!");
}
}
And here’s the result:
You can see that the Speak method was overridden.