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

前端 未结 2 1083
遇见更好的自我
遇见更好的自我 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: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.

提交回复
热议问题