Tutorial Thursday - Global variables in ActionScript 3.0
Ohi.
Been a while, ain’t it?
Here’s a small and sweet post about Flash.
A global variable is a variable that you can call throughout your program.
For instance, if you are making a game, and you want to add points to the score and display it in the top right of the screen, you would make a global variable varScore and call it twice.
Now, in ActionScript 2.0, this was fairly straightforward:
//define your variable
_global.varScore = 0;
//call your variable (adding 100 points)
_global.varScore += 100;
Now, apparantly, Adobe figured this was too easy or something, and they gave the programmers a big fat middle finger when it came to global variables.
This, apparantly, because if you have a global variable in your code, and you don’t know where each instance is, and you change it somewhere, you might not know its value.
Even though, you could, like, do
trace(_global.varScore); //this will give you its value!!!
So they decided to not have global variables alltogether.
Yes, that’s right.
Thank the Flying Spaghetti Monster, there is a way to have global variables in ActionScript 3.0.
-make a new ActionScript file, call it GlobalVars.as
-in this file, write the following:
package
{
public class GlobalVars
{
//stuff!
}
}
-at the stuff, write your global variables like so:
public static varScore:Number = 100;
-to call your variable, first import your ActionScript file, like so:
import GlobalVars;
-and then, finally, you have global variables:
GlobalVars.varScore += 100;
This took me three days and 12 forum posts to figure out.
Fuck you Adobe.
-knite
Tags: actionscript, flash, programming

April 29th, 2008 at 7:41 pm
Doesn’t seem to work for me.
Throws following error inn the as file:
1071: Syntax error: expected a definition keyword (such as function) after attribute public, not static.
July 9th, 2008 at 10:06 am
The correct should be:
public static var varScore:Number = 100;
NOT
public static varScore:Number = 100;