Game Development Reference
In-Depth Information
With this code, some improvement is made, that is, different classes are created for
each NPC type, namely, ManCharacter , WomanCharacter , and OrcCharacter . Each
offers a different greeting in the SayGreeting function. Further, each NPC inherits
all the common behaviors from the shared base class MyCharacter . However, a
technical problem regarding type specificity arises. Now, imagine creating a tavern
location inside which there are many NPCs of the different types defined, so far, all
enjoying a tankard of grog. As the player enters the tavern, all NPCs should offer
their unique greeting. To achieve this functionality, it'd be great if we could have
a single array of all NPCs and simply call their SayGreeting function from a loop,
each offering their own greeting. However, it seems, initially, that we cannot do this.
This is because all elements in a single array must be of the same data type, such as
MyCharacter[] or OrcCharacter[] . We cannot mix types for the same array. We
could, of course, declare multiple arrays for each NPC type, but this feels awkward
and doesn't easily allow for the seamless creation of more NPC types after the array
code has been written. To solve this problem, we'll need a specific and dedicated
solution. This is where polymorphism comes to the rescue. Refer to the following
sample 1-14, which defines a new Tavern class in a completely separate script file:
01 using UnityEngine;
02 using System.Collections;
03
04 public class Tavern : MonoBehaviour
05 {
06 //Array of NPCs in tavern
07 public MyCharacter[] Characters = null;
08 //-------------------------------------------------------
09 // Use this for initialization
10 void Start () {
11
12 //New array - 5 NPCs in tavern
13 Characters = new MyCharacter[5];
14
15 //Add characters of different types to array MyCharacter
16 Characters[0] = new ManCharacter();
17 Characters[1] = new WomanCharacter();
18 Characters[2] = new OrcCharacter();
19 Characters[3] = new ManCharacter();
20 Characters[4] = new WomanCharacter();
21
22 //Now run enter tavern functionality
23 EnterTavern();
24 }
25 //-------------------------------------------------------
 
Search WWH ::




Custom Search