简体   繁体   中英

How to execute an as3 script from another as3 script in flash?

I have two as3 files file1.as and file2.as. When a user presses a button in file1.as I want it to execute file2.as. And if someone presses a button in file2.as i want it to go back to file1.as.

Is this possible? Can i attach file2.as to frame 2 and then use gotoAndStop(2) from within file1.as.

Thank you.

As there are no sample codes in your question, I will try to give a general answer.

In ActionScript 3 .as files (should) correspond to classes, and you should really think this in terms of OOP. Without resorting to scripts in the frames, what you should really be doing is to condense file2.as into a class, or a method inside a class. Then you may instantiate an object of that class (executing your logic in the constructor) when the button is pressed. Or just instantiate it beforehand and call its method when you want it to be executed.

Also, it seems that what you are trying to do would really benefit from the events and listeners concept in AS3.

Edit: modified sample code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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