Game Development Reference
In-Depth Information
The for loop
The foreach loop is handy when you need to iterate through a single array
sequentially from start to end, processing each element one at a time. But
sometimes you need more control over the iterations. You might need to process
a loop backwards from the end to the start, you might need to process two arrays
of equal length simultaneously, or you might need to process every alternate array
element as opposed to every element. You can achieve this using the for loop, as
shown here:
//Repeat code backwards for all objects in array, one by one
for(int i = MyObjects.Length-1; i >= 0; i--)
{
//Destroy object
DestroyMyObjects[i]);
}
The following are the comments for the preceding code snippet:
• Here, the for loop traverses the MyObjects array backwards from the end
to the start, deleting each GameObject in the scene. It does this using a local
variable i . This is sometimes known as an Iterator variable, because it
controls how the loop progresses.
• The for loop line has the following three main parts, each separated by a
semicolon character:
° i : This is initialized to MyObjects.Length - 1 (the last element
in the array). Remember that arrays are zero-indexed, so the last
element is always Array Length -1 . This ensures that loop
iteration begins at the array end.
° i >= 0 : This expression indicates the condition when the loop
should terminate. The i variable acts like a countdown variable,
decrementing backwards through the array. In this case, the loop
should end when i is no longer greater than or equal to 0 , because
0 represents the start of the array.
° i-- : This expression controls how the variable i changes on each
iteration of the loop moving from the array end to the beginning.
Here, i will be decremented by one on each iteration, that is,
a value of 1 will be subtracted from i on each pass of the loop.
In contrast, the statement ++ will add 1 .
• During the loop, the expression MyObjects[i] is used to access
array elements.
 
Search WWH ::




Custom Search