Search code examples
actionscript-3children

as3: how to use grandchildren? ex. getChildByName("name").getChildByName("name2")


I'm looking for a method, to get dynamically created children of a display object instance in ?

trace(_view.getChildByName("name")) //returns name of display object (success)

trace(_view.getChildByName("name").getChildByName("name2")) //returns error 1061

Solution

  • Yes, you can. The problem is that DisplayObjectContainer.getChildByName() returns type DisplayObject, and an arbitrary display object may or may not be a DisplayObjectContainer. So, while you can do that, you first need to cast the type of the result to a DisplayObjectContainer:

    public static function getGrandChildByName(
             parent : DisplayObjectContainer,
             child : String,
             grandchild : String
    ) : DisplayObject {
        var child_obj : DisplayObject = parent.getChildByName(child);
        var child_container : DisplayObjectContainer = child_obj as DisplayObjectContainer;
        return child_container.getChildByName(grandchild);
    }
    

    Note that in the example I gave above, I didn't do any checking to verify that the child is actually exists and is a DisplayObjectContainer.... in actual production code, you might want to add such checks.

    Also, one last note, if you are using type MovieClip, you can simply refer to the object by its name:

      myclip.mc_child.mc_grandchild.gotoAndStop(3);
    

    Simply refering to the elements by name is simpler and less error-prone. I highly recommend it.