Variables Across Classes


(Noah) #1

Is there a way to make a variable accessible by all classes in my project?

Sorry for being kinda a noob at this.


(Jacob Albano) #2

There is, but be very careful when doing so.

// viewable and changeable by any class in the game
public static var highScore:int;

// viewable and changeable only by instances of the class you declare it in
private static var totalBananas:int;

// viewable by any class in your game, but never able to be changed
public static const gameName:String = "My awesome game!";

// viewable by any class in your game, but only changeable by instances of this class
private static var _data:int;
public static function get data():int {
    return _data;
}

private static function set data(value:int):void {
    _data= value;
}

Whereas normally you access variables through a class instance:

trace(myObject.someVar);

with static properties you access them through the class itself:

trace(MyClass.someStaticVar);

A word of warning: when you start using global variables it’s really easy to keep using global variables for everything. Using them too often can introduce bugs where you’re setting a variable in the wrong place and messing things up, or causing order-of-operations errors where data isn’t guaranteed to be the same as you left it last. Try to minimize their use whenever you can. This is my opinion, obviously, and there are folks on this forum who feel differently, but I’ve found that global state is usually more trouble than it’s worth and the more you can work around using it, the better.