PDA

View Full Version : Passing variables between classes


jameskyle
08-21-2010, 05:25 PM
Hi. I'm making the jump to AS3 and working with classes and I'm having a little trouble understanding where I'm going wrong. I have a series of variables in my document class that I'd like to be able to access in other classes, though I'm not sure how I'd manage this, as no amount of experimenting with parent, root, Main, etc. seems to bring anything but compile errors. I'll show what I have so far:

document class "Main.as"
package {

import flash.display.MovieClip;
public class Main extends MovieClip {

public var healthSpending:Number = 1;

public function Main() {
}
}
}

Second class:

package {

import flash.display.MovieClip;
public class titleScreen extends MovieClip {

public function titleScreen() {
trace(healthSpending); // returns possibly undeclared variable error.

}
}
}

How would I access the variable healthSpending declared in the document class from within the second class?

remo5000
08-24-2010, 01:25 AM
You should be able to access the variable from the second class as the HealthSpending variable is public. :)

tadster
08-24-2010, 02:52 AM
if the two classes are in the same folder and have the same package structure,
you could do this:

public function titleScreen() {
var aMain:Main = new Main();
trace(aMain.healthSpending);

}


But I think what you want is this:

package {

import flash.display.MovieClip;
public class Main extends MovieClip {

public var healthSpending:Number = 1;

public function Main() {
addChild(new titleScreen(this));
}
}
}



package {

import flash.display.MovieClip;
public class titleScreen extends MovieClip {

public function titleScreen(mainReference:Main) {
trace(mainReference.healthSpending); // no error now
}
}
}