Hero Placeholder needs something to command

I’ve got this error, maybe someone could help me out? am i doing something wrong?

Let’s play it through:

var soldiers = this.findFriends();        // soldiers.length = 1 for this run
var soldierIndex = 0;
while(soldiers.length > soldierIndex)     //1 > 0 is true
{
    soldierIndex += 1;                    //soldierIndex == 1
    var soldier = soldiers[soldierIndex]; //soldier == soldiers[1] == null

    this.command(soldier, ...);           //this.command(null, ...);
}

You’re problem is simply that you increase the soldierIndex too early. As a rule of thumb you should always increase the index as the last thing in your loop so that exactly this can not happen.

2 Likes

thank you very much, I have one more question that keeps reoccurring (in relation to while loops), sometimes when i declare a variable outside of the while loop the code doesn’t work, what kind of rules are there for declaring variables? i know there’s global and local when it comes to functions, is it the same with loops?

for example here,

    while (soldiers.length > soldierIndex) {
        var soldier = soldiers[soldierIndex];
        this.command(soldier, "attack", enemy);
        soldierIndex++;
    }

if i change it to this, it doesn’t work

var soldier = soldiers[soldierIndex];
while (soldiers.length > soldierIndex) {
        
        this.command(soldier, "attack", enemy);
        soldierIndex++;
    }

The above command line is commanding soldier, and soldier only gets assigned once before the loop. The purpose of the loop is to step through all the soldiers by updating the index and assigning the new value to soldier, so if soldier value isn’t being updated each iterations, you’re only acting on a single soldier.

Also, soldierIndex should always be assigned 0 before the loop is run to start at the beginning of the array. A for loop is more efficient at assigning these loop variables and automatically incrementing them.