Flash actionscript 2 was great for _global or root variables or values. With actionscript 3 ‘_global’ and ‘root’ are not longer valid markup. Since AS3 is object oriented scripting, those methods of assigning values are no longer valid. So, the question is: how do I use global or root variables in Flash AS3 (actionscript 3). Here is a method that I use on projects where I need to have a work around and utilize a variable that will be called in multiple functions across the timeline.
First, I create an actionscript file (.as) with my variable names and their types declared within a class, in this case I called my class ‘MyGlobal’.
package {
public class MyGlobal {
public static var myTotal:int;
public static var myArray:Array = new Array();
public static var mySting:String = new String();
}
}
Save this file as ‘MyGlobal.as’.
Next, create a new Flash file (.fla) and save it in the same location as the MyGlobal.as file. When we create our swf file the .as file will be compiled.
In the .fla file we need to import our class that we have created.
import MyGlobal;
Now we can assign values to these variables within the .fla file and utilize them anywhere. Just remember to use the class name MyGlobal in front of the variable name in the constructor.
MyGlobal.myTotal = 22;
MyGlobal.myArray.push(“value1″);
MyGlobal.myArray.push(“value2″);
MyGlobal.myArray.push(“value3″);
MyGlobal.myString = “this is a string”;
That’s it. Global variables are alive and well in Flash AS. Have fun!
Related Posts:
Posted in: Flash Helps | Comments Off