Flash AS3 Error controlling button from external a

2019-07-29 11:34发布

问题:

Help. Basically i have 2 button at different frame. If the button on frame 1 clicked, it will go to and stop at frame 2. If the button on frame 2 clicked, it will go to and stop at frame 1. What I'm trying to do is controlling this button over external actionscript file. The 1st button running with no problem, while the 2nd one seems to not responding properly and have this error message:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at src::Main/init()
    at src::Main()

Here's the code:

package src 
{
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.MovieClip;

/**
 * ...
 * @author vimoetz
 */
public class Main extends MovieClip 
{

    public function Main():void 
    {
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);
    }

    private function init(e:Event = null):void 
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        this.gotoAndStop("1");
        button1.addEventListener(MouseEvent.CLICK, gotoFrame2);
        button2.addEventListener(MouseEvent.CLICK, gotoFrame1);
    }

    public function gotoFrame2 (e:MouseEvent)
    {
        this.gotoAndStop("2");
    }

    public function gotoFrame1 (e:MouseEvent)
    {
        this.gotoAndStop("1");
    }

}

}

回答1:

You need to remove this line from your init function:

button2.addEventListener(MouseEvent.CLICK, gotoFrame1);

and the function gotoFrame2 change like this:

public function gotoFrame2 (e:MouseEvent)
    {
      this.gotoAndStop("2");
      if (!button2.hasEventListener(MouseEvent.CLICK)){
        button2.addEventListener(MouseEvent.CLICK, gotoFrame1);
      }
    }