How to pass variables from .fla file to .as file in as3

134 views Asked by At

I have a .fla file names test.fla and I have this variable in it:

import Main;

var my_var;

stage.addEventListener(MouseEvent.CLICK, onLoaded);

function onLoaded(e:Event):void
{
 my_var = "Maziar";
 //trace(my_var);
}

I have a .as file called Main.as.

I want to pass my_var from test.fla to the Main.as.

I will really appreciate, if you can help me in this matter!

It is noticeable that I have used the method mentioned in "Actionscript 3 : pass a variable from the main fla to external as file", but it does not work for me!!!

I wrote in my Main.as:

package 
{
import flash.display.Sprite;
import flash.geom.Point;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;

public class Main extends Sprite
{
    public function Main()
    {
        if (stage)
        {
            init();
        }
        else
        {
            addEventListener(Event.ADDED_TO_STAGE, init);

        }

        addEventListener(Event.ENTER_FRAME, waitForMyVar);
    }

    private function waitForMyVar(e:Event):void
    {
        if (my_var != null)
        {
            trace(my_var);
            removeEventListener(Event.ENTER_FRAME, waitForMyVar);
        }

    }

    private function init(e:Event = null):void
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);
    }
 ...
 }
}

Thanks in advance!

2

There are 2 answers

8
phasma On

It's important to note that the constructor Main in your ActionScript document file is run before the code found within the frame. When you are attempting to access the my_var variable in your AS document it has not yet been declared in the frame.

So, we need to wait for Flash to run the frame. This can be done using an Event.ENTER_FRAME listener.

Example:

Timeline Code (.fla file)

var my_var:String = "my variable";

Document Code (.as file)

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

    public class Main extends MovieClip {
        public function Main() {
            addEventListener(Event.ENTER_FRAME, waitForMyVar);
        }

    private function waitForMyVar(e:Event):void {
        trace(my_var);
        removeEventListener(Event.ENTER_FRAME, waitForMyVar);
    }
}

As a side note, it appears my_var is not assigned a value until the user has clicked the stage. An adjustment could be made in the waitForMyVar function to wait for my_var to be non-null.

Example:

if(my_var != null) {
    trace(my_var);
    removeEventListener(Event.ENTER_FRAME, waitForMyVar);
}

Hope this helps!

0
Organis On

Use static class members.

public class Main extends Sprite
{
    static public var globalVar:* = 1;

    public function doWhatever():void
    {
        trace(globalVar);
    }
}

Then in FLA:

import Main;

var M:Main = new Main();
// or use sprite instance of Main

M.doWhatever();
Main.globalVar = "Hello World!";
M.doWhatever();