LIBGDX - SetScreen nullpointer异常

时间:2013-08-03 22:20:18

标签: java nullpointerexception libgdx

我实际上遇到了libgdx的问题。

TypingGame.java

public class TypingGame extends Game {

TypingGame game;

GameScreen gameScreen;
GameOverScreen gameOverScreen;

@Override
public void create() {      

    gameScreen = new GameScreen();
    gameOverScreen = new GameOverScreen(game);

    Texture.setEnforcePotImages(false);
    setScreen(new GameScreen()); // Default screen : Gamescreen

}


}

我希望能够使用setScreen更改当前屏幕。这是我做的:

GameScreen.java

public class GameScreen implements Screen, InputProcessor{

private World world;
private WorldRenderer renderer;
private WorldController controller;
TypingGame game;


@Override
public void render(float delta) {

    Gdx.gl.glClearColor(0.5f, 0.1f, 0.1f, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    Timer.elapsedTime(delta);
    renderer.render(delta);
    controller.update(delta);


    if(Player.health == 0) game.setScreen(new GameOverScreen(game)); // If the player died, switch to GameOverScreen
}

// And so on...

GameOverScreen.java

public class GameOverScreen implements Screen{


TypingGame game;
GameScreen gameScreen;

public GameOverScreen(TypingGame game){
    this.game = game;
    gameScreen = new GameScreen();
}

@Override
public void render(float delta) {


    Gdx.gl.glClearColor(0.5f, 0.1f, 0.1f, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

}

@Override
public void resize(int width, int height) {


}

@Override
public void show() {


}

@Override
public void hide() {

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void dispose() {

}

}

我无法弄清楚为什么会出现这个错误:

Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: java.lang.NullPointerException
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:113)
Caused by: java.lang.NullPointerException

这应该很容易使用,但我能实际使用setScreen的唯一类是...... TypingGame.java。

非常感谢你的帮助,谢谢你的不良英语。

Cya!

2 个答案:

答案 0 :(得分:2)

在您的TypingGame类中,您不会创建自己的新实例:

TypingGame game; //------------------ this!
...
gameOverScreen = new GameOverScreen(game); //----you don't pass the new "game", you pass "this"

你也必须对GameScreen做同样的事情。

gameScreen = new GameScreen(this); //---like this

您正在获得NPE,因为在GameScreen中您正在尝试使用不存在的游戏。您需要使用“this”将TypingGame实例传递给GameScreen,并将其存储在:

TypingGame game;
你的GameScreen的

另外作为旁注(但非常重要!),您正在创建GameScreen的实例和GameOverScreen的实例,但每次设置屏幕时都会创建一个新的...

答案 1 :(得分:0)

另外,为什么要创建一个新的gameScreen,然后不在setScreen()中使用它?

gameScreen = new GameScreen();
gameOverScreen = new GameOverScreen(game);

Texture.setEnforcePotImages(false);
setScreen(new GameScreen()); // Default screen : Gamescreen

我希望最后一行读取:setScreen(gameScreen);