sigvardsen
sigvardsen

Reputation: 1531

Looping through childs in actionscript-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;
}

Upvotes: 3

Views: 14713

Answers (4)

David
David

Reputation: 5456

Not sure if for each works, but this works.

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

Upvotes: 13

Eric Lavoie
Eric Lavoie

Reputation: 11

My two cents.

    public static function traceDisplayList(displayObject:DisplayObject, maxDepth:int = 100, skipClass:Class = null, levelSpace:String = " ", currentDepth:int = 0):void 
    {
        if (skipClass != null) if (displayObject is skipClass) return;
        trace(levelSpace + displayObject.name);  // or any function that clean instance name
        if (displayObject is DisplayObjectContainer && currentDepth < maxDepth)
        {       
            for (var i:int = 0; i < DisplayObjectContainer(displayObject).numChildren; i++)
            {
                traceDisplayList(DisplayObjectContainer(displayObject).getChildAt(i), maxDepth, skipClass, levelSpace + "    ", currentDepth + 1);
            }
        }
    }   

Upvotes: 1

DexTer
DexTer

Reputation: 2103

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.

Upvotes: 2

back2dos
back2dos

Reputation: 15623

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)) {
    //....
}

greetz

back2dos

Upvotes: 2

Related Questions