How to use a WHILE LOOP? Obviously not inside ***function Update***

I used a while loop as follows:

//while myBoolean is true, I want the gameObject's tag to become "HotObject" (and 
//obviously when myBoolean turns false, the tag will be reverted back to what it was).
function Update () {
        while (myBoolean)   {

As many of you must have already guessed, this freezes Unity. I searched for relevant questions a bit and I learned that while loops inside function Update freeze Unity. So how would I use the aformentioned loop? (and a happy 2011 everybody!)

Infinite loops freeze Unity, no matter where they are. (Actually they just crash it; a much nicer alternative. thanks devs!)

If you want something to be true while something else is true, you don't use while. Update is its own "while( game playing )" function (of sorts). You use ifs:

if ( ready ) tag = awesome;
else if ( !ready ) tag = notawesome;

Whiles (as explained above) are for conditions that exit eventually -

while ( transform has children ) {
  AFunction( childZero ); 

Okay, lets take a look at the while-loop:


A while-loop keeps executing its code, while its condition is true. E.g.

var i : int = 0;

while (i < 10)
    Debug.Log("Index i is: " + i);


This will print:

Index i is: 0

Index i is: 1

Index i is: 2

Index i is: 3

Index i is: 4

Index i is: 5

Index i is: 6

Index i is: 7

Index i is: 8

Index i is: 9

It stops there, because i = 10 does not satisfy the condition: i < 10.

You can also do this with an for-loop, e.g.:

for (var i : int = 0; i < 10; i++)
    Debug.Log("Index i is: " + i);

A while loop in Update() does not make the program "freeze", but given the condition you gave the while-loop will make it loop forever, until its condition is false.

You can use (for javascript)

while (condition) {
yield WaitForSeconds (0);

but not use on update function