Loops

A loop is what we use in scripting to do the same commands multiple time.  We use these in many different situations, such as, searching inventories for an item.

for loop – The for loop is the one that we use the most.  To set it up we need to give it three pieces of information.  First we declare a variable to keep track of how many times the loop has run.  Next is the condition to test to see if we need to continue the loop.  Last we increment the counter variable.  When the loop starts it sets up the variable.  Then it checks the condition – if the condition is true it does the commands.  After doing all commands it increments the counter and checks the condition to see if the loop should run again.  It keeps looping until the condition is no longer true, at which point, it exits the loop.

Example:  In this example the numbers 0 through 9 will be printed in the console.

for(int i = 0; i < 10; i++)
{
Debug.Log(i);
}

 while Loop

A while loop is similar to a for loop except that it only needs the condition to check in it’s parenthesis.  We don’t use while loops very often as for loops do the jobs we usually need a loop to do.

Example of while loop:

while(conditionIsTrue)
{
//Do instructions
}