Unity – Loops – FOR – WHILE – DO WHILE – FOR EACH

In Unity loops can execute a block of code a number of times.

FOR

#pragma strict

var numEnemies : int = 3;


function Start ()
{
    for(var i : int = 0; i < numEnemies; i++)
    {
        Debug.Log("Creating enemy number: " + i);
    }
}

The result is:
Creating enemy number: 0
Creating enemy number: 1
Creating enemy number: 2

WHILE

#pragma strict

var cupsInTheSink : int = 4;


function Start ()
{
    while(cupsInTheSink > 0)
    {
        Debug.Log ("I've washed a cup!");
        cupsInTheSink--;
    }
}

The result is:
I’ve washed a cup! (number 4)
I’ve washed a cup! (number 3)
I’ve washed a cup! (number 2)
I’ve washed a cup! (number 1)

DO WHILE

#pragma strict

function Start()
{
    var shouldContinue : Boolean = false;
        
    do
    {
        print ("Hello World");
            
    }while(shouldContinue == true);
}
[

The result is:
Hello World if shouldContinue == true

<h2>FOR EACH and ARRAYS</h2>

#pragma strict

function Start () 
{
    var strings = ["First string", "Second string", "Third string"];
    
    for(var item : String in strings)
    {
        print (item);
    }
}

The result is:

First string
Second string
Third string