Game Development Reference
In-Depth Information
Debug.Log (PickedCard.Name);
}
}
//------------------------------------------
}
//------------------------------------------
IEnumerable and IEnumerator
When you're working with collections of data, whether List , Dictionary , Stack , or
others, you'll typically want to iterate (or traverse) all items in the list or at least some
items, based on a specific criteria. In some cases, you'll want to loop through all items
in sequence or some items. Most often, you'll want to traverse the items forwards in
sequence, but as we've seen, there are times when reverse traversing is also suitable.
You can loop through items using a standard for loop. However, this raises some
annoyances that the interfaces of IEnumerable and IEnumerator can help us solve.
Let's see what the annoyances are. Consider the for loop in the following code
sample 6-5:
//Create a total variable
int Total = 0;
//Loop through List object, from left to right
for(int i=0; i<MyList.Count; i++)
{
//Pick number from list
int MyNumber = MyList[i];
//Increment total
Total += MyNumber;
}
There are three main annoyances while using a for loop. Let's start with the first
two. The first is that the syntax is not especially inviting for a loop that just cycles
from left to right, from beginning to end, and we must always use an integer iterator
variable ( i ) to access each array element as the loop proceeds. The second is that the
iterator itself is not truly "bounds safe". It can, in fact, be incremented or decremented
either above or below the array limits and cause an out-of-bounds error.
 
Search WWH ::




Custom Search