Owen James
Owen James

Reputation: 628

Target main .as file in ActionScript 3

I am trying to target a variable in the main .as file (The one that acts as the stage) from another .as file.

public var stageRef:MovieClip = root as MovieClip;

or

MovieClip(root)variable = 10;

don't seem to want to work for me. Neither of them produce any compile errors but when I try to use them they give me a 1009 error, cannot access a property or a null object reference. Any ideas of how i would go about doing this? Thanks in advance.

Upvotes: 0

Views: 172

Answers (1)

Creative Magic
Creative Magic

Reputation: 3141

Im your Main.as class make the variable public. Here's an example:

package
{
    import flash.display.Sprite;

    public class Main extends Sprite
    {
        public var YOUR_VAR_HERE:VARIABLE_TYPE = DEFAULT_VALUE;
        public function Main()
        {

        }

    }
}

DEFAULT_VALUE is optional. VARIABLE_TYPE is recommended, if not specified the type will be Object by default.

There are many ways to pass a variable to another class. If the class is created inside the Main class, just pass the variable to that class like this:

var myOtherClass:OtherClass = new OtherClass(YOUR_VAR_HERE);

or

var myOtherClass:OtherClass = new OtherClass();
myOtherClass.varReference = YOUR_VAR_HERE;

In first case make sure the constructor is expecting a variable. In the second, make sure the OtherClass has a public variable varReference that you can access and modify.

Another way loved by newbie programmers are static (singleton) variables: in the Main class specify your variable as such:

public static var YOUR_VAR_HERE:VARIABLE_TYPE = DEFAULT_VALUE;

Then you can access YOUR_VAR_HERE simply by referring to the class Main. Like this:

trace(Main.YOUR_VAR_HERE);

NOTE: it's considered to use all uppercase letters for constants, not variables, in this case I used all caps for readability.

Upvotes: 1

Related Questions