Removing specific DisplayObjects from a container in Actionscript 3

Actionscript Add comments

This is a common mistake when trying to remove certain DisplayObject objects from a container in Actionscript. I fell into it again today and kicked myself around the office for five minutes afterward.

If you want to remove specific DisplayObjects from a container you may be tempted to do something like this …

  1. for (i=0; i<container_mc.numChildren; i++)
  2.    {
  3.     if(container.getChildAt(i) == mySprite || container_mc.getChildAt(i) == anotherSprite) container_mc.removeChildAt(i);
  4.    }

This will work unless one of the Sprites is at the top of the stack in which case that object wont be removed. But WHY?!!!

Well because the numChildren property will reduce as the objects get removed so eventually it will stop before the last object. The solution is to compensate by adjusting the variable ‘i’ in the for loop. Like so …

  1. for (i=0; i<container_mc.numChildren; i++)
  2.    {
  3.     if(container.getChildAt(i) == mySprite || container_mc.getChildAt(i) == anotherSprite) { container_mc.removeChildAt(i); i–;}
  4.    }

Hope this helps someone and prevents any self-harm.

Digg!

3 Responses to “Removing specific DisplayObjects from a container in Actionscript 3”

  1. Peter deHaan Says:

    I haven’t tried it, but wouldn’t it be better to do a decrementing loop from numChildren to 0 instead? At least that way you may not have to try and adjust indices due to removed items.

    Peter

  2. admin Says:

    Wouldn’t there still be a situation where a child could be skipped as numChildren changes?

  3. M. Bruno Correia Says:

    There’s no need to use DisplayObject::numChildren at all. The following not only works correctly, but is also more efficient.


    // using your example here - I have no idea why 'container' is being searched for if
    // it's not removed anyway?

    var i: int = numChildren;
    while(--i >= 0)
    {
    if(container.getChildAt(i) == mySprite || container_mc.getChildAt(i) == anotherSprite)
    container_mc.removeChildAt(i);
    }

    However there’s much better ways to do this other than linear search but I guess that depends on the number of objects on the display list tree.

Leave a Reply

 
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in