Search code examples
javalibgdx

Libgdx: Unexplainable NullPointerException on Singleton


Might only be answerable with libGDX skills.

MyGame.java:

public void create() { // gets called after constructor
        Resources.setInstance(new Resources());
}

Resources.java

public static void setInstance(Resources res) {
        if (instance != null) {
            instance = res;
        }
        else throw new IllegalStateException(
                "instance cant be null");
}

Stacktrace:

Exception in thread "LWJGL Application" java.lang.IllegalStateException: instance cant be null
    at com.mutant.td.Resources.setInstance(Resources.java:22)
    at com.mutant.td.SpeciesWarGame.create(SpeciesWarGame.java:41)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:143)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)

I have literally no idea what is going on.


Solution

  • This is wrong:

     if (instance != null)
    

    You're checking the wrong thing here. You should be checking:

     if (res != null)
    

    As this is the thing you're passing into your method.