Search code examples
actionscript-3recursionflash-cs4

recursively getting all children, grandchildren, etc of stage in as3


This is my first time using recursion in actionscript so I'm sure that there is something I'm not accounting for. What I'm trying to do is just iterate through stage children and trace out what the child is and the index. Here is some code.

    public function recurseStage(dOC:DisplayObjectContainer)
    {
        var numCh = dOC.numChildren;
        for(var i = 0; i < numCh; i++)
        {
            var child = dOC.getChildAt(i);  
            trace("child: " + child + " at i: " + i);

            if(child.numChildren > 0)
            {
                recurseStage(child);
            }
        }
    }

the problem area seems to be the actual recurseStage() call at the end. As well as the if statement before that. I know not all children will have the property .numChildren but I'm not sure what to use instead. This should be an easy fix but my brain just isn't helping me out right now. Also if there is a better way than this please let me know. Thanks in advance.


Solution

  • use
    if (child is DisplayObjectContainer && child.numChildren > 0)

    instead of

    if(child.numChildren > 0)