This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Cookie Policy. X

From AS2 to AS3: _global equivalent in AS3 [basic]

I once was asked is there a way to access variables that were set on _root or _global. The problem comes from how strict the ActionScript3 is - in AS2 you would just write _global.myVar = 5 and then access it from anywhere, but AS3 just doesn't tolerate dynamic variables (and also there is no _global keyword).
There are two ways to work around it:

1. Use syntax meant for dynamic variables.

root["myVar"] = 5;
It is almost the same thing as in AS2, but since you are using dynamic variables you might find yourself with an extremely slow application (when used excessively). If that is the case you should consider the second option.

2. Use static keyword.
This is probably the most proper way to do it, but requires some additional work. Before you do anything create a "Document Class", which you will find in the properties tab.

Type in any name you want for you class (e.g. "MyClass"), confirm it with enter key (at this point a warning should pop-up saying the class doesn't exist - ignore it) and then click the pencil icon on the side.
If done correctly, new class file should be created in a separate window looking something like this:

package  {
	import flash.display.MovieClip;
	public class MyClass extends MovieClip {
		public function MyClass() {
			// constructor code
Now just before the public function MyClass() line, type in:
public static var myVar:Number = 5;
That is pretty much it. From anywhere in your project you can now access this variable through class identifier, for example:
import MyClass;
Also, since you document class is used as "root" object, you can now access it through root field of each MovieClip. It needs to be casted to your class beforehand though:
import MyClass;
trace((root as MyClass).myVar);

Confirm the image code:confirm image