Search code examples
haxeopenfl

Acces non-static data from static initialization of static field in Haxe


I'm trying to initialize a static class field in Haxe with a Float value, but the compiler complains about the initializer being invalid.

I don't have a lot of experience using Haxe, so if anyone can help me I would be really grateful.

Here is the code:

Enemy.hx

And here is the error:

cmd


Solution

  • "Invalid field access" is basically a null reference error, meaning that Lib.current.stage is null at the time that static fields are initialized. As a workaround, you could use a property with a getter so that it's accessed later:

    public static var radius(get, never):Float;
    
    private static function get_radius():Float
    {
        return Lib.current.stage.stageWidth / 35;
    }