如何从flash中的另一个as3脚本执行as3脚本?

时间:2011-01-01 22:34:56

标签: flash actionscript-3 events

我有两个as3文件file1.as和file2.as。当用户按下file1.as中的按钮时,我希望它执行file2.as。如果有人按下file2.as中的按钮,我希望它返回到file1.as。

这可能吗?我可以将file2.as附加到第2帧,然后在file1.as中使用gotoAndStop(2)。

谢谢。

1 个答案:

答案 0 :(得分:2)

由于您的问题中没有示例代码,我将尝试给出一般答案。

在ActionScript 3中.as文件(应该)对应于类,您应该根据OOP来考虑这一点。如果不使用框架中的脚本,您应该真正做的是将file2.as压缩为类或类中的方法。然后,当按下按钮时,您可以实例化该类的对象(在构造函数中执行逻辑)。或者只是事先将其实例化,并在需要执行时调用它的方法。

此外,您尝试做的事情似乎真的会受益于AS3中的事件和听众概念。

编辑:修改过的示例代码:

A.as:

class A {
    public var myButton:Sprite;
    protected var myPong:B;

    public function A() {
        myButton.addEventListener(MouseEvent.CLICK, onClick)
    }

    protected function onClick(e:MouseEvent):void {
        myPong = new B();
        addChild(myPong);
        myPong.addEventListener("pong_closed", onPongClosed);
        myPong.startGame();
    }

    protected function onPongClosed(e:Event):void {
        myPong.removeEventListener("pong_closed", onPongClosed);
        removeChild(myPong);
        myPong = null;
    }
}

B.as:

class B {
    public function B() {
        // Game initialization code.
    }

    public function startGame():void {
        trace("ping ... pong ... ping ... pong ... ping");
    }

    public function close():void {
        trace("Closing Pong");
        // Your destruction code goes here.
        // ...
        dispatchEvent(new Event("pong_closed"));
    }
}
相关问题