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

}

}
3
  • 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. Commented Apr 30, 2013 at 8: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. Commented Apr 30, 2013 at 8:43
  • This method works too. Thank you :) Commented Apr 30, 2013 at 10:18

1 Answer 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);
      }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.