Game Development Reference
In-Depth Information
These issues can, to some extent, be fixed using the neater foreach loop, which is
bounds safe and uses a simpler syntax, as shown in following code sample 6-6:
//Create a total variable
int Total = 0;
//Loop through List object, from left to right
foreach(int Number in MyList)
{
//Increment total
Total += Number;
}
The foreach loop is simpler and is to be preferred for readability, but there's more
going on here than first meets the eye. The foreach loop works only for classes that
implement the IEnumerable interface. Objects that implement IEnumerable must
return a valid instance to an IEnumerator interface. So, for an object to work in a
foreach loop, it must depend on two other interfaces. The question that then arises is
why is there all this internal complexity for simple looping or traversal behavior. The
answer is, not only do the IEnumerable and IEnumerator solve the first two problems
of simpler syntax and bounds-safe iteration by way of the foreach loop, but they also
solve a third problem. Specifically, they allow us to loop through or iterate groups
of objects that are not even truly array types; that is, they let us iterate through many
different types of objects, whether or not they're in an array, as though they were in an
array. This can be very powerful. Let's see this in action in a practical example.
Iterating through enemies with IEnumerator
Take, for example, an RPG game that features a medieval world inhabited by many
different and evil wizard characters (coded in class Wizard ). For the sake of example,
these wizards will spawn into the level at random places and random intervals,
potentially causing untold trouble for the gamer, casting spells, and performing evil
deeds. The result of such random spawning is that, by default, we cannot know in
advance how many wizards there will be in the scene at any one time, nor can we
know where they've been spawned, because it's random. However, there are still
legitimate reasons why we'd need to find all the wizards; perhaps, all the wizards
must be disabled, hidden, paused, or killed, or, perhaps, we need a head count to
prevent overspawning. So, regardless of the wizard spawning and its randomness,
there are still good justifications for being able to access all the wizards in the level
on demand.
 
Search WWH ::




Custom Search