Rajesh Rajesh - 18 days ago 5
ActionScript Question

Referring stage from the class Action Script 3

Basically I am coding to switch between scenes by clicking buttons. I am giving frame label sand scene names as arguments. MovieClip(root).gotoAndStop(frameLabel, sceneName); works fine on the stage. But when I use the same on class it throws the warning TypeError: Error #1009: Cannot access a property or method of a null object reference. I know it happens as there is no root for the class.Is there any way to fix it. Please find the code below.

//class code

package {
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.display.SimpleButton;
import flash.display.*;
import flash.text.*;
import flash.events.Event;
import flash.display.MovieClip;

public class ClickButton extends SimpleButton {
public var fLabel:String;
public var sName:String;
public var sNumber:Number;

public function ClickButton()
{

}

public function GotoSession(sesBut:SimpleButton, frameLabel:String, sceneName:String):void {
sesBut.addEventListener(MouseEvent.CLICK, gotoSes);
function gotoSes(event:MouseEvent):void {
MovieClip(root).gotoAndStop(frameLabel, sceneName);
}
}
}


//AS3 code

var btn1 = new ClickButton();
addChild(btn1);
btn1.GotoSession(home, "menu", "Home");

Answer

You have two problems here, and I don't really understand why You work like this but,

1 : When I try to compile your code, I get an compile time Error :

There miss a "}" at the end of Your Class.

I removed what's not used:

package {
    import flash.events.MouseEvent;
    import flash.display.SimpleButton;
    import flash.display.MovieClip;
    public class ClickButton extends SimpleButton {
        public function ClickButton() {
        }
        public function GotoSession(sesBut:SimpleButton,frameLabel:String,sceneName:String):void {
            sesBut.addEventListener(MouseEvent.CLICK,gotoSes);
            function gotoSes(event:MouseEvent):void {
                MovieClip(root).gotoAndStop(frameLabel,sceneName);
            }
        }
    }
}

I suppose that you have a button in Your Library linked to the ClickButton Class as here below:

enter image description here

So :

var btn1:ClickButton = new ClickButton();
addChild(btn1);
btn1.GotoSession(btn1, "menu", "Home");
stop();

If I click on btn1, this brings me to the scene "Home" at the label "menu".

This works like a charm.

on the frameLabel "menu" :

stop();
trace("currentScene.name = " + this.currentScene.name);
trace("currentFrameLabel = " + this.currentFrameLabel);

/*
OUTPUT : 
currentScene.name = Home
currentFrameLabel = menu
*/

but I don't understand Your line :

//btn1.GotoSession(home, "menu", "Home");

home is null (You don't have any reference to a ClickButton named home)...???