简体   繁体   English

如何使用as3类访问舞台上的movieClip?

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

public class MyClass extends MovieClip {
            public function MyClass():void {
                my_mc.addEventListener(MouseEvent.CLICK, action);
            }
            private function action(e:MouseEvent):void {
                trace("cliked");
            }
        }

Timeline code 时间线代码

 var myClass:MyClass = new MyClass();
    addChild(myClass);

I can't able to access the my_mc (placed in FLA) movieclip. 我无法访问my_mc (放置在FLA中)movieclip。 How do I access? 我如何访问?

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 . 如果这不起作用(我认为不会这样),那是因为你的my_mc显示对象不是舞台的子MainTimeline ,而是MainTimeline实例的子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. 如果我的假设是正确的, my_mcmyClass显示对象共享同一个父对象。

If my_mc is a MovieClip on the stage of MyClass, you may be trying to access it too early. 如果my_mc是MyClass舞台上的MovieClip,您可能会尝试过早访问它。 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 : 构造函数代码通常在绘制第一帧之前执行,因此您需要通过侦听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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM