Game Development Reference
In-Depth Information
12 //--------------------------------------------------
13 // Update is called once per frame
14 void Update ()
15 {
16 }
17 }
The following are the comments for code sample 1-11:
•
Line 04
: The class
NewScript
is derived from
MonoBehaviour
. You can,
however, substitute
MonoBehaviour
for almost any valid class name from
which you want to derive.
•
Line 10
: Here, the variable name is assigned a string during the
Start
event.
However, notice that the name is not explicitly declared as a variable anywhere
in the
NewScript
source file. If
NewScript
were a completely new class with
no ancestor defined in line 04, then line 10 would be invalid. However, because
NewScript
derives from
MonoBehaviour
, it automatically inherits all of its
variables, allowing us to access and edit them from
NewScript
.
When to inherit
Only use inheritance where it's really appropriate; otherwise, you'll
make your classes large, heavy, and confusing. If you're creating
a class that shares a lot of common functionality with another and
it makes sense to establish connection between them, then use
inheritance. Another use of inheritance, as we'll see next, is when
you want to override specific functions.
Classes and polymorphism
To illustrate polymorphism in C#, let's start by considering the following code
sample 1-12. This sample doesn't demonstrate polymorphism immediately but
represents the start of a scenario where polymorphism will be useful, as we'll see.
Here, a basic skeleton class is defined for a potential
non-player character
(
NPC
) in
a generic RPG game. The class is intentionally not comprehensive and features basic
variables that only mark the starting point for a character. The most important thing
here is that the class features a
SayGreeting
function, which should be invoked
when the player engages the NPC in conversation. It displays a generic welcome
message to
Console
as follows:
01 using UnityEngine;
02 using System.Collections;