Game Development Reference
In-Depth Information
Classes and inheritance
Imagine a scenario where you create an Orc class to encode an orc object in the
game. Having done so, you then decide to make two upgraded types. One is an Orc
Warlord, with better armor and weapons, and the other is an Orc Mage who, as the
name implies, is a spell caster. Both can do everything that the ordinary orc can do,
but more besides. Now, to implement this, you can create three separate classes, Orc ,
OrcWarlord , and OrcMage , by copying and pasting common code between them.
The problem is that as Orc Warlord and Orc Mage share a lot of common ground and
behaviors with orc, a lot of code will be wastefully copied and pasted to replicate the
common behaviors. Furthermore, if you discovered a bug in the shared code of one
class, you'd need to copy and paste the fix to the other classes to propagate it. This is
both tedious and technically dangerous, as it risks wasting time, introducing bugs,
and causing needless confusion. Instead, the object-oriented concept of inheritance can
help us. Inheritance allows you to create a completely new class that implicitly absorbs
or contains the functionality of another class, that is, it allows you to build a new class
that extends an existing class without affecting the original one. When inheritance
happens, two classes are brought into a relationship with each other. The original
class (such as the Orc class) is known as the case class or ancestor class. The new class
(such as the Orc Warlord or Orc Mage), which extends on the ancestor class, is called a
super class or derived class.
More information on inheritance in C# can be found at
http://msdn.microsoft.com/en-gb/library/
ms173149%28v=vs.80%29.aspx .
By default, every new Unity script file creates a new class derived from
MonoBehaviour . This means every new script contains all the MonoBehaviour
functionality and has the potential to go beyond, based on the additional code
that you add. To prove this, refer to the following code sample 1-11:
01 using UnityEngine;
02 using System.Collections;
03
04 public class NewScript : MonoBehaviour
05 {
06 //--------------------------------------------------
07 // Use this for initialization
08 void Start ()
09 {
10 name = "NewObject";
11 }
 
Search WWH ::




Custom Search