Game Development Reference
In-Depth Information
Classes and object-oriented
programming
A class is an amalgam of many related variables and functions, all brought together
into a self-contained unit or "thing". To put it another way, if you think about a game
(such as a fantasy RPG), it's filled with many independent things such as wizards,
orcs, trees, houses, the player, quests, inventory items, weapons, spells, doorways,
bridges, force fields, portals, guards, and so on. Many of these objects parallel objects
in the real world too. However, crucially, each of these things is an independent
object; a wizard is different and separate from a force field, and a guard is different
and separate from a tree. Each of these things, then, can be thought of as an object—a
custom type. If we focus our attention on one specific object, an orc enemy, for
example, we can identify the properties and behaviors in this object. The orc will
have a position, rotation, and scale; these correspond to variables.
The orc might have several kinds of attacks too, such as a melee attack with an axe
and a ranged attack with a crossbow. These attacks are performed through functions.
In this way, a collection of variables and functions are brought together into a
meaningful relationship. The process of bringing these things together is known as
encapsulation. In this example, an orc has been encapsulated into a class. The class,
in this case, represents the template for a general, abstract orc (the concept of an
orc). Objects, in contrast, are particular, concrete instantiations of the Orc class in
the level. In Unity, script files define a class. To instantiate the class as an object in
the level, add it to GameObject . As we've seen, classes are attached to game objects
as components. Components are objects, and multiple components together form a
GameObject . Refer to code sample 1-10 for a sample Orc class stub:
01 using UnityEngine;
02 using System.Collections;
03
04 public class Orc : MonoBehaviour
05 {
06 //Reference to the transform component of orc (position,
rotation, scale)
07 private Transform ThisTransform = null;
08
09 //Enum for states of orc
10 public enum OrcStates {NEUTRAL, ATTACK_MELEE, ATTACK_RANGE};
11
12 //Current state of orc
13 public OrcStates CurrentState = OrcStates.NEUTRAL;
14
15 //Movement speed of orc in meters per second
16 public float OrcSpeed = 10.0f;
 
Search WWH ::




Custom Search