Search code examples
haxehaxeflixel

HaxeFlixel: How to call a getter/setter variable in another class


I'm building a basic game to learn the ins and outs of HaxeFlixel and want to call a variable with getter/setter properties from MenuState in the PlayState. Code looks something like this:

class MenuState extends FlxState
{
    @:isVar public var myVar(get, null):Bool;

    public function get_myVar():Bool
    {
      return myVar;
    }
}

class PlayState extends FlxState
{
    private var _foo:Bool;

    override public function create():Void
    {
        // var ms = new MenuState; doing it like this doesn't return anything
        _foo = MenuState.get_myVar();
        if (_foo)
        {
            // do this thing
        }
        else
        {
            // do that thing
        }
    }
}

With the ms variable it returns do that thing, without it I get an error Class<MenuState> has no field get_myVar. I'm sure that's probably not how to write the code, but at this point I'm just trying to get it to work. Essentially what I'm trying to do is get the MenuState to write a variable that the PlayState reads but can't write. How would I got about doing that?


Solution

  • myVar and the getter function in MenuState are not static in your code, so you cannot access them like MenuState.get_myVar(). I think making myVar static would be an ok solution to your problem.

    You do not need to call get_myVar() directly. The getter will be called whenever you access myVar outside of MenuState. You can test that by adding a trace("message"); to get_myVar.