- Home /
What is the order of execution in a for loop?
Suppose you have three blocks positioned side by side. Will this code:
var once = false
for (var block : GameObject in blocks){
if (!once){
turn45degrees(block)
}
once = true;
}
A) Turn all the blocks (turn45degrees() on each block, then set once to true three times)
B) Turn one block (turn45degrees() on the first block, then set once to true, so the other blocks can't turn)
Answer by Epicwolf · Aug 08, 2013 at 05:16 PM
B. For loops just repeat the same segment of code multiple times. The order of execution doesn't change. (In other words, think of the loop as a mini function that is called until a condition is met.)
If I have another block of code:
function Update(){
var aVariable : float
//here
if (!isDead){
aVariable = 1
} else {
aVariable = 2
}
}
After Update() executes once, and then starts executing again, will the variable's value be 1 or 2 when it reaches //here for the second time, or will the variable be redeclared and be null when it reaches //here for the second time?
"aVariable" is a local variable. So when Update is finished the variable is gone and when Update is called again a new variable is "created". However your example doesn't make any sense since it lacks of context. What is isDead? where is it declared? where is it set? what's it's value?
I was making things up to show that each time Update() runs, a value is set to aVariable. I basically wanted to know if the variable's value remains when Update() keeps getting called.