MaxG
MaxG

Reputation: 213

Looping and Removing Children stored in Array

I have an Array that holds a few MCs... There is a reset in my app that clears the array and removes the MCs from the stage. It works fine if I test one at a time like this:

if (myArray.length > 0)
            {
            removeChild(myArray[0]);
            }

However if I try to iterate through the Array somehow as to remove all the objects (pr even just one in this case) it doesn't seem to know what the parent object is and therefore can't remove it. I've tried explicitly tell it myArray[0].parent.(removeChild(...) but It throws the same error. Currently I'm trying this:

while (myArray.length > 0)
        {
            removeChild(myArray[0]); // this line 'must be a child of the caller'
        }

Other kinds of loops return the same error. If I trace the objects parent it prints the correct object too... So I'm at a loss. Am I missing something obvious or is there a better way to do this?

Upvotes: 0

Views: 343

Answers (1)

Pan
Pan

Reputation: 2101

Your code will always try to remove the first element in myArray. So first time you could remove the element, and the element isn't the child of his parent anymore.When in the second time, you are trying to remove the first element again and as the element has no parent(it was removed last time), it will give you an error.

So you should remove each element in the array, not same element.

Try this

while (myArray.length > 0)
{
   var mc = myArray.shift();
   removeChild(mc);
}

If you don't want to remove element in myArray, you can use a count to save if you have remove all elements.Or just use for each like you did.

var count:int = 0;

while (count < myArray.length)
{
   var mc = myArray[count];
   removeChild(mc);
   count++;
}

Upvotes: 2

Related Questions