A question about some codes

> def commandTroops():
>     for friend in friends:
>         enemy = friend.findNearestEnemy()
>         if enemy:
>             hero.command(friend, "attack", enemy)

When i use friend.findNearestEnemy(), in some levels it works, and some levels it says can’t read protected property. I don’t know why. does somebody know the logic behind this?

Did you define friends?

1 Like

@Seojin_Roy_Lee Yes, i define friends in the loop while true.

That won’t work. A variable that is defined inside one loop or function cannot be seen in or used in another loop or function. In the function that you have shown here, you must define the variables you use inside it.

1 Like

Yep. you will need to pass “friends” through the function, like:

def commandTroops(friends):
     for friend in friends:
         enemy = friend.findNearestEnemy()
         if enemy:
             hero.command(friend, "attack", enemy)

Notice the fact the “friends” is in the function, and when you run the function, it will need to look something like this:

commandTroops(friends)

Hope that helps!

1 Like

and you have to define friends before you activate commandTroops(friends).

2 Likes

Yep. I just assumed that was already done, but good point :smiley:

1 Like