Been searching and have not been able to find an aswer.
I am trying to set a value in a class from another class. Tried different ways of doing it by doing it the way I know from other languages but I cannot seem to be able to it in OpenFL
basically I have class like this
var myClass:Newclass = new Newcllass;
myClass.someVar = "some value";
then the class is something like this:
class Newcllass extends Sprite{
public var someVar:String;
public function getSomeVarValue(){
trace(someVar);
}
}
This returns null. Can someone point me in the right direction please?
It seems that you need to understand more about OOP itself. Haxe manual (https://haxe.org/manual/introduction.html) will help you with all of the things you are asking here.
First of all, you are not trying to access variable in class, but in object here. If you want your class to have variables, you need to use word static.
I have the type defined in the class it is set like this:
public var selectedPlayer:String;
I understand that. But that is not my question. I ended up creating a function to handle the setting of the variable. I was simply trying to assign that variable a value by doing this:
gameHelper.selectedPlayer = "Johnie";
instead I did:
gameHelper.setPlayer("Johnie");
in the game class I have a function:
public function setPlayer(player){
this.selectedPlayer = player;
trace(this.selectedPlayer);
}
However, if you try to access selectedPlayer before setting selectedPlayer, it won’t work. Consider this code: at first it prints “null” because selectedPlayer hasn’t been set, but later, it prints the correct value.
class Game extends Sprite {
public var selectedPlayer:String;
public function new(){
super();
makePlayer();
}
public function makePlayer(){
trace(selectedPlayer);// this was returning null
}
}
from my Main class I was trying to set it like this:
gameHelpers = new Game();
gameHelpers.selectedPlayer="Johnie";
addChild(gameHelpers);
to get around the null issue I added the function in the game class to set the value of selectedPlayer
from main I now do this:
class Main extends Sprite{
...
public function someFunction(){
gameHelpers = new Game();
gameHelpers.setPlayer("Johnie");
}
}
then in the game Class
class Game extends Sprite {
...
public function setPlayer(player){
this.selectedPlayer = player;
trace(this.selectedPlayer);
}
}