Game Development Reference
In-Depth Information
•
Lines 13, 23, and 29
: The
WizardEnumerator
class implements the methods
and properties of
IEnumerator
, specifically,
MoveNext
(which iterates over to
the next wizard in the cycle),
Reset
(which resets the iterator back to the first
wizard), and
Current
(which returns the active wizard in the cycle).
•
Line 39
: The
Wizard
class encapsulates a wizard character in the scene and
inherits from two classes:
MonoBehaviour
and
IEnumerable
. This means
that all the features of both classes come together in this derived class. It
internally maintains several variables that allow the enumerator to loop
through all the wizard instances in the scene at any time. First,
Wizard
holds
the
FirstCreated
and
LastCreated
static members (which are global to all
the wizard instances). These variables are set when objects are created (see
the
Awake
function in line 58).
FirstCreated
always refers to the instance of
a wizard that was created first, and
LastCreated
always to the most recently
created instance.
•
Lines 48 and 52
: The
Wizard
class also maintains the instance variables,
NextWizard
and
PrevWizard
. This implements a doubly-linked list; that
is, each instance of the wizard points to the previously and subsequently
created instance, which allows a chain-like connection between all wizards.
The first wizard will have
PrevWizard
or
null
, and the last wizard will have
NextWizard
or
null
. These variables make it possible for the iterator to cycle
through all wizard instances even when none of them are in an array.
•
Line 86
: The
GetEnumerator
method returns an instance to an
Enumerator
object. This is required by the
IEnumerable
interface and allows a
foreach
loop across all wizards.
Together, the
Wizard
and
WizardEnumerator
classes offer fast, direct, and
efficient
Wizard
object cycling, even though no array of wizards need to truly
exist. To see this in practice, in a scene of wizards, the following code sample 6-9
can enumerate all wizards:
void Update()
{
//Press space to list all wizards in scene
if(Input.GetKeyDown(KeyCode.Space))
{
//Get first wizard through static member
Wizard WizardCollection= Wizard.FirstCreated;
//If there is at least one wizard, then loop them all
if(Wizard.FirstCreated != null)
{
//Loop through all wizards in foreach
foreach(Wizard W in WizardCollection)