Game Development Reference
In-Depth Information
03
04 public class MyCharacter
05 {
06 public string CharName = "";
07 public int Health = 100;
08 public int Strength = 100;
09 public float Speed = 10.0f;
10 public bool isAwake = true;
11
12 //Offer greeting to the player when entering conversation
13 public virtual void SayGreeting()
14 {
15 Debug.Log ("Hello, my friend");
16 }
17 }
The first problem to arise relates to the diversity and believability of the MyCharacter
class if we try imagining how it'd really work in a game. Specifically, every character
instantiated from MyCharacter will offer exactly the same greeting when SayGreeting
is invoked: men, women, orcs, and everybody. They'll all say the same thing, namely,
"Hello, my friend" . This is neither believable nor desirable. Perhaps, the most
elegant solution would be to just add a public string variable to the class, thus allowing
customization over the message printed. However, to illustrate polymorphism clearly,
let's try a different solution. We could create several additional classes instead, all
derived from MyCharacter , one for each new NPC type and each offering a unique
greeting from a SayGreeting function. This is possible with MyCharacter , because
SayGreeting has been declared using the virtual keyword (line 13). This allows
derived classes to override the behavior of SayGreeting in the MyCharacter class.
This means the SayGreeting function in derived classes will replace the behavior of
the original function in the base class. Such a solution might look similar to the code
sample 1-13:
01 using UnityEngine;
02 using System.Collections;
03 //-------------------------------------------
04 public class MyCharacter
05 {
06 public string CharName = "";
 
Search WWH ::




Custom Search