Game Development Reference
In-Depth Information
function Start () {
while(numberOfTires < 4)
{
Debug.Log("I replaced an old tire on my car!");
numberOfTires++;
}
}
Breaking it down shows the following parts:
(1) (2)
while(numberOfTires < 4)
(3)
{
(4)
Debug.Log("I replaced an old tire on my car!");
numberOfTires++;
(5)
}
1.
The
while
keyword.
2.
The conditional statement.
3. Open braces for the body of the
while
loop.
4. The statement block that contains the code to be executed on each iteration
of the
while
loop.
5. The close braces for the body of the
while
loop. Just as with the
for
loop,
the
while
loop ends with the close braces rather than a semicolon.
One of the biggest differences here, and a common cause of problems, is that if your conditional
expression never evaluates to
false
, the
while
loop continues to run. This is what is known as an
infinite loop
—something you do not want your game trapped in!
Run the script and you will see that you have put four new tires on your car. You could rewrite these
simple examples using either a
for
loop or a
while
loop interchangeably. You will get a feel for the
subtle difference between them when choosing to use one or the other as you continue to apply
them in real game development scenarios.
As a rule of thumb,
for
loops are more commonly used in more precisely defined situations, such
as when the number of loops to be executed is predetermined or if the same variable is used for the
initial value, the conditional statement, and as the increment.
The
do-while
Loop
Just like the
for
loop, if the conditional for a
while
loop never resolves to
true
, then the statement
block is never executed. There will be times when you want your statement block run at least once
before the conditional is tested. The
do-while
loop expands on the
while
loop to give you this ability.