Tuesday, August 25, 2009

Access variables passed from HTML in AS3

In AS2 accessing variables passed into Flash from a web page was as easy as referencing _root.{whatever}. AS3 makes things a little more complicated. Why? Just because. Deal with it.


// myVariable is the name of a var passed to the SWF, as in
// <EMBED ...>FlashVars="myVariable=Hello"
// or even
// mymovie.swf?myVariable=Hello

var myVariable:String = LoaderInfo(loaderInfo).parameters["myVariable"] || "defaultValue";
trace(myVariable);
// "Hello"


While working in the IDE, or if the page doesn't supply the proper variable, the "parameters" object property will be undefined. It's always best to set a default value, which is what that
|| "defaultValue"
bit is about.

If you have a lot of variables you need to access... well first off you should consider reading an XML file for configuration, but if that's too much trouble, try this, just for convenience:


var flashVars:Object = new Object();
for (var name in LoaderInfo(loaderInfo).parameters) {
this[name] = LoaderInfo(loaderInfo).parameters[name];
}
// now you can access variables like:
trace(this.myVariable);
// very much like the old AS2 _root.myVariable

No comments: