AS3 Gotcha #3: “_global” and passing variables to externally loaded SWFs

So, controversial debates aside, you can’t use _global in AS3 anymore.

It was easy to use _global in AS2 to create a variable that could be accessed from anywhere in your project: from the main timeline to any timeline inside of any movie clip of your project, even ones loaded dynamically or externally.

The problem usually came when you passed your project over to someone else, and you had to combine files, and they happened to use the same global variable name as you did. Then you’d run into trouble.

But now that _global‘s all done away with in AS3, how do you pass or set variables you’ve created yourself from one SWF to another?*

Solution: create a public class with a public static variable that can be accessed from anywhere. If you’ve used any of the major ActionScript tweening frameworks (I use Tweener), you’ve already used a public static class.

If you’re unfamiliar (or lazy), no worries. I’ve already created a class you can use yourself:

//a public static class to simulate the good old days of “_global” in AS2
//usage: declare your “global” variable as such:
//MoGlobal.g.theVariable

package {
   public class MoGlobal {
      public static var g:Object = new Object();
   }
}


Copy and paste the above code into a new .as file called “MoGlobal.as” and put that file into your ActionScript 3.0 class directory.

In your main timeline (or wherever you want to, quite frankly) declare your brand spankin’ new global public static variable:

MoGlobal.g.myFakeGlobal;

But, if you need to set an initial value for it, then of course it would look more like:

MoGlobal.g.myFakeGlobal = “initial value”;

Now, you can (re)set the variable from wherever you need to, ideally from an externally loaded SWF:

MoGlobal.g.myFakeGlobal = “new value”;

You can of course also just access it to use its value to fill in the value of any other variable within the new SWF:

var myString:String = MoGlobal.g.myFakeGlobal;

Now, arguably, this is entirely better than _global for two reasons:

1) The chances of you and another designer/developer using the same exact public static variable as you are pretty slim—unless of course everybody decides to download this particular MoGlobal class and use it.

2) You get to feel cool for using a something as fancy as a “public static class” and kinda know what you’re talking about.

Now, granted, I could be shot down by some in the AS3 community for trying to duplicate the same functionality and principals behind _global but, hey: it works, right? And that’s what we like.

Now get (back) to work.


About this entry