1

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

}

}
MPelletier
  • 16,256
  • 15
  • 86
  • 137
vimoetz
  • 13
  • 2
  • 1
    You should have both buttons on the first frame, extending to the second and then set button.visible depending on which frame you are. – Kodiak Apr 30 '13 at 08:14
  • Your problem is here "Basically i have 2 button at different frame. " Your 2 buttons must be on the first frame, when you add the listeners (you can set visible to false for the second button if you dont want it to be visible on stage). Or use the Cherniv solution to only add the listener of button 2 on second frame. – RafH Apr 30 '13 at 08:43
  • This method works too. Thank you :) – vimoetz Apr 30 '13 at 10:18

1 Answers1

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);
      }
    }
Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146
  • RafH answered you below already. Interesting part is this: button2.hasEventListener(MouseEvent.CLICK) which means "to add click listener only once" (for prevent 'gotoFrame1' function running multiple times after each click) – Ivan Chernykh Apr 30 '13 at 10:31