How do I access a movieClip on the stage using as3 class?

十年热恋 提交于 2019-11-29 05:08:39

Try this:

public class MyClass extends MovieClip
{
    public function MyClass()
    {
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);

    }// end function

    private function init(e:Event = null):void 
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);

        var myMc:MovieClip = stage.getChildByName("my_mc") as MovieClip;
        // var myMc:MovieClip = parent.getChildByName("my_mc") as MovieClip;

        myMc.addEventListener(MouseEvent.CLICK, onMyMcClick)

    }// end function

    private function onMyMcClick(e:MouseEvent)
    {
        trace("clicked");

    }// end function

}// end class

If this doesn't work(which I don't think it will), its because your my_mc display object isn't a child of the stage, but the child of an instance of MainTimeline. If so, then simply comment out the following statement in the above code:

var myMc:MovieClip = stage.getChildByName("my_mc") as MovieClip;

and uncomment the following statement in the above code:

// var myMc:MovieClip = parent.getChildByName("my_mc") as MovieClip;

If my assumption is correct, the my_mc and myClass display objects share the same parent.

If my_mc is a MovieClip on the stage of MyClass, you may be trying to access it too early. Constructor code generally executes before the first frame is drawn, so you need to wait for that drawing to take place by listening for Event.ADDED_TO_STAGE:

public class MyClass extends MovieClip {
    public function MyClass():void {
        if(stage) {
            init();
        } else {
            addEventListener(Event.ADDED_TO_STAGE,init);
        }
    }

    private function init(e:Event = null):void {
        if(e) removeEventListener(Event.ADDED_TO_STAGE,init);
        stage.my_mc.addEventListener(MouseEvent.CLICK, action);
    }

    private function action(e:MouseEvent):void {
        trace("cliked");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!