views:

957

answers:

3

How do you loop through all the childs in a DisplayObjectContainer in as3? I would like a syntax like this:

for each(var displayObject:DisplayObject in displayObjectContainer )
{
    displayObject.x += 10;
    displayObject.y += 10;
}
+2  A: 

Not sure if for each works, but this works.

var i:int = 0;
for (i = 0; i<myObj.numChildren; i++)
{
    trace(myObj.getChildAt(i));
}
David
+1  A: 

something like this maybe?

function getChildren(target:DisplayObjectContainer):Array {
 var count:uint = target.numChildren;
 var ret:Array = [];
 for (var i:int = 0; i < count; i++) 
  ret.push(target.getChildAt(0));
 return ret;
}

and then

for each (var child:Array in getChildren(displayObjectContainer)) {
    //....
}
back2dos
A: 

You can use following recursive function to iterate through all children of any DisplayObjectContainer class.

function getChildren(dsObject:DisplayObjectContainer, iDepth:int = 0):void
{
     var i:int = 0;
     var sDummyTabs:String = "";
     var dsoChild:DisplayObject;

     for (i ; i < iDepth ; i++)
      sDummyTabs += "\t";

     trace(sDummyTabs + dsObject);

     for (i = 0; i < dsObject.numChildren ; ++i)
     {
      dsoChild = dsObject.getChildAt(i);
      if (dsoChild is DisplayObjectContainer && 0 < DisplayObjectContainer(dsoChild).numChildren)
       getChildren(dsoChild as DisplayObjectContainer,++iDepth);
      else
       trace(sDummyTabs + "\t" + dsoChild);
     }
}

It will display all children in hierarchical manner exactly as DisplayList tree.

Bhavesh.Bagadiya