sutoL
sutoL

Reputation: 1767

for each loop in adobe flash

C:\Users\ifcdu1\Desktop\MTWater\src\Fish.as:87: 1067: Implicit coercion of a value of type String to an unrelated type Food.

can someone tell me why i am getting this error? i am trying to access the x,y values of a object of type Food in my array which holds food objects

public function loop(e:Event):void
{
    if(foodInPond > 0)
    {
        var foodArray:Array = foodDroppedArray;
        for (var i:Food in foodDroppedArray);
        {
            if (getDistance(this.x - foodDroppedArray[i].x , this.y - foodDroppedArray[i].y) < 100)
            {
                if(!i.eaten)
                {
                    moveToFood(newFood);
                }
                else if (i.eaten)
                {
                    updatePosition();
                }
            }
            else
            {
                updatePosition();
            }
        }

    }
    else
    {
        updatePosition();
    }
}

Upvotes: 1

Views: 1224

Answers (3)

Marty
Marty

Reputation: 39466

for each(var i:Food in foodDroppedArray)
{
    if(getDistance(this.x - i.x , this.y - i.y) < 100)
    {
        if(!i.eaten)
            moveToFood(newFood);
        else if(i.eaten)
            updatePosition();
        else
            updatePosition();
    }
}

You forgot to add the each keyword after for. Also, you originally had:

if(getDistance(this.x - foodDroppedArray[i].x , this.y - foodDroppedArray[i].y) < 100)

foodDroppedArray[i] would have been invalid (null) here, you just need to use i like you did in the latter parts of the loop.

Upvotes: 1

Adam Harte
Adam Harte

Reputation: 10530

The "for each" loop needs the "each" part, and you should not put in a semi-colon(;) at the end of the line. So it should look like this:

for each (var i:Food in foodDroppedArray)
{
    if (getDistance(this.x - foodDroppedArray[i].x , this.y - foodDroppedArray[i].y) < 100)
    {
        if(!i.eaten)
        {
            moveToFood(newFood);
        }
        else if (i.eaten)
        {
            updatePosition();
        }
    }
    else
    {
        updatePosition();
    }
}

Upvotes: 2

Samuel Neff
Samuel Neff

Reputation: 74949

You're just missing each:

                for each (var i:Food in foodDroppedArray);

ActionScript has three for loops, for, for..in, and for each..in. The first loops through a counter. The second loops through keys of an object. The last loops through values in a collection.

Upvotes: 0

Related Questions