Book Image

Mastering Unity Scripting

By : Alan Thorn
Book Image

Mastering Unity Scripting

By: Alan Thorn

Overview of this book

Table of Contents (17 chapters)
Mastering Unity Scripting
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...