Graphics Reference
In-Depth Information
If we were building a game with lots of cars in it, having to rewrite the car class for
each type of car would be silly. A far more efficient method might be to write a base class
and populate it with virtual functions. When we need to create a car, rather than use this
base class, we build a new class, which inherits the base class. Because our new class is
inherited, it is optional whether or not we choose to override the Wheels or Engine func-
tion to make them behave in ways specific to our new class. That is, we can build “default”
functions into the base class, and if we only need to use a default behavior for an engine,
our new class doesn't need to override the engine function.
The base class might look something like this:
public class BaseCar : MonoBehavior {
public virtual void Engine () {
Debug.Log("Vroom");
}
public virtual void Wheels () {
Debug.Log("Four wheels");
}
}
There are two key things to notice in the above script. One is the class declaration
itself and the fact that this class derives from MonoBehavior. MonoBehavior is itself a
class—the Unity documentation describes it as “the base class every script derives from”—
this  MonoBehavior class contains many engine-specific functions and methods such as
Start(), Update(), FixedUpdate(), and more. If our script didn't derive from MonoBehavior,
it would not inherit those functions, and the engine wouldn't automatically call functions
like Update() for us to be able to work with. Another point to note is that MonoBehavior
is a class that is built in to the engine and not something we can access to edit or change.
The second point to note is that our functions are both declared as virtual functions.
Both are public and virtual. Making virtual functions means that the behavior in our base
class may be overridden by any scripts that derive from it. The behavior we define in this
base class could be thought of as its default behavior. We will cover overriding in full a
little further on in this section.
Let's take a look at what this script actually does: If we were to call the Engine() func-
tion of our BaseCar class, it would write to the console “Vroom.” If we called Wheels, the
console would read “Four wheels.”
Now that we have our BaseCar class, we can use this as a template and make new ver-
sions of it like this:
public class OctoCar : BaseCar {
public override void Wheels () {
Debug.Log("Eight wheels");
}
}
The first thing you may notice is that the OctoCar class derives from BaseCar rather
than from MonoBehavior. This means that OctoCar inherits the functions and methods
belonging to our BaseCar script. As the functions described by BaseCar were virtual, they
may be overridden. For OctoCar, we override Wheels with the line:
public override void Wheels () {
Search WWH ::




Custom Search