Game Development Reference
In-Depth Information
We've seen already, in Chapter 2 , Debugging , one way in which we can retrieve a
traversable list of all wizards, as shown in the following code sample 6-7:
//Get all wizards
Wizard[] WizardsInScene = Object.FindObjectsOfType<Wizard>();
//Cycle through wizards
foreach (Wizard W in WizardsInScene)
{
//Access each wizard through W
}
The problem with the FindObjectsOfType function is that it's slow and performance
prohibitive when used frequently. Even the Unity documentation at http://docs.
unity3d.com/ScriptReference/Object.FindObjectsOfType.html recommends
against its repeated use.
A sample Unity project using the IEnumerator and IEnumerable
interfaces can be found in the topic's companion iles (code bundle) at
Chapter06\Enumerators .
So, instead, we can achieve similar behavior using IEnumerable and IEnumerator ,
and this avoids significant performance penalties. Using these two interfaces, we'll be
able to efficiently iterate through all the wizards in the scene, using a foreach loop,
as though they were in an array, as shown in the following code sample 6-8:
01 using UnityEngine;
02 using System.Collections;
03 using System.Collections.Generic;
04 //----------------------------------------------------
05 //Class derives from IEnumerator
06 //Handles bounds safe iteration of all wizards in scene
07 public class WizardEnumerator : IEnumerator
08 {
09 //Current wizard object pointed to by enumerator
10 private Wizard CurrentObj = null;
11 //----------------------------------------------------
12 //Overrides movenext
13 public bool MoveNext()
14 {
15 //Get next wizard
16 CurrentObj = (CurrentObj==null) ? Wizard.FirstCreated :
CurrentObj.NextWizard;
17
 
Search WWH ::




Custom Search