Diogo Saito Takeuchi
Diogo Saito Takeuchi

Reputation: 17

Problems getting objects in Stage

So, im using this code to remove a couple of movie clips from my stage:

for (var i:uint = 0; i < this.numChildren; i++)
{
    if (this.getChildAt(i) is MovieClip
        && pecasInGame.indexOf(this.getChildAt(i)) >= 0)
    {
        removeChild(this.getChildAt(i));
    }
}

But its not really working well... I have 5 movie clips to remove and they are all added dinamically, when these movieclips are added i insert then into this array "pecasInGame", and when there is five of then I try to remove using the aforementioned loop.

The problem is, it only removes 3 of then, the 0, 2 and 4 objects.. The 1 and 3 arent even listed in the loop. Any idea why would that happen??

Upvotes: 0

Views: 115

Answers (2)

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

The problem is you are iterating over the children and removing at the same time, so the indices of the children are changing, which is causing the problem.

If you want to remove all the movie clips from the display list, do something like this :

for each(var mc:MovieClip in pecasInGame)
{
     if(getChildIndex(mc) != -1)
         removeChild(mc);
}

Upvotes: 1

Sr.Richie
Sr.Richie

Reputation: 5740

You're removing the display objects, so the indexes are changing WHILE your loop goes on. Change it this way:

for (var i:uint = this.numChildren-1; i >= 0 ; i--)
{
    if (this.getChildAt(i) is MovieClip && pecasInGame.indexOf(this.getChildAt(i)) >= 0)
    {
        removeChild(this.getChildAt(i));
    }
}

Other option: use your array to remove the objects, like this

for (var i:int=0; i<pecasInGames.length; i++) {
     removeChild (pecasInGames[i]);
}

Upvotes: 2

Related Questions