Inconsistency with For Loop

Hi,

I have a question regarding for loops. Here’s a snippet of code:

public var heart : GameObject;
public var maxHeart : int;
public var i : int;

function Update() {
  for (i=0; i<maxHeart; i++) {
     instantiate(heart,Vector3(i*20,0,0),Quaternion.Identity);
  }
}

In the inspector, I set the maxHeart to 4. When I click play the i stops at 4 but instantiates non stop in the scene. Why is it behaving like that when the condition of the loop is if it’s less than maxHeart?

So I replace the for loop with while loop instead:

while(i < maxHeart) {
  i++;
  instantiate(heart,Vector3(i*20,0,0),Quaternion.Identity);
}

and this bloody works. I would like to know why the for loop is behaving like this when both of the functions are similar.

Because the for loop is setting i back to 0 every Update and the while loop isn’t.

The for loop has 3 parts:

for (PART1; PART2; PART3)

PART1 is executed one time when the for loop is entered, this is usually used to initialize a variable like you did.

PART2 is a condition which is checked reight before each iteration. If it’s false the for loop is terminated.

PART3 is executed right after each iteration. It’s used to prepare the next iteration step.

You problem is that you set the variable i to 0 each time you execute the code (which is every frame since you have it in Update).

Btw, You really shouldn’t use a public instance variable as for loop variable. for loops usually use local variables. Also the name “i” is ok as local temporal variable in a vor loop, but as instance variable the name doesn’t make much sense.