Storing SWFObject.addVariable() vars globally in AS3

Embedding variables with SWFObject is easy. In previous versions of Actionscript all the variables registered with the SWFObject were globally available within the SWF. From any class or object, you could call _root.theVariableName and access that variable.

However, moving to AS3, things are a little different. The SWFObject still embeds FlashPlayer 9 content without a problem – the SWF is properly embedded into the HTML and all the variables and parameters passed to the SWFObject are registered with the SWF. The only difference in AS3 is that these variables are not automatically available throughout your FLA.

So use SWFObject like you always do:

<div id="flashcontent">you need to get the new flash player</div>

<script type="text/javascript">
    var so = new SWFObject("/swfs/yourswf.swf", "yourswf_flash", "550", "400", "9");
        so.addParam("scale", "noscale");
        so.addVariable("varOne", 1); 
        so.addVariable("varTwo", "two");

Then in your Document class you can reference the parameters property of its loaderInfo property like this:


It’s a little more work than before, but its not too bad. Now comes the global stuff…

A little background… The global _root reference is no longer available in AS3. In fact, there are no built in global references at all in AS3. DisplayObjects in AS3 all have a root property, but that property refers back to the base class of the DisplayObject. So your DocumentClass’ (the base class of your FLA) root property references the Stage, but if you had another Sprite on the stage called Sprite1 its root property would not reference the Stage, but itself.

Now lets look at how to store those variables globally. We just need to create a class with a static object variable that we can add our variables to, like so:

    import flash.display.Sprite;
    import com.greenethumb.utils.GlobalVarContainer;

    public class Main extends Sprite
        public function Main()
            GlobalVarContainer.vars.varOne  = this.loaderInfo.parameters.varOne;
            GlobalVarContainer.vars.varTwo  = this.loaderInfo.parameters.varTwo;

For more detailed explanation of this GlobalVarContainer see this post .

So that covers taking a variable passed to Flash from the SWFObject embed and storing it in a globally accessible place in your AS3 project. To retrieve those vars, just import the GlobalVarContainer class into any other class and access GlobalVarContainer.vars._yourVariableName_. Done!

2 Responses to 'Storing SWFObject.addVariable() vars globally in AS3'

  1. Andy See says:

    Thanks for the great article. Is there any way to pass Flashvars to a swf that I want to load from within my swf?

Leave a Reply to Andy See Cancel reply

Your email address will not be published. Required fields are marked *