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

前端 未结 2 1084
遇见更好的自我
遇见更好的自我 2020-12-17 04:10
public class MyClass extends MovieClip {
            public function MyClass():void {
                my_mc.addEventListener(MouseEvent.CLICK, action);
            }         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 04:33

    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");
        }
    }
    

提交回复
热议问题