2013-08-03 54 views
0

我實際上遇到了libgdx的問題。LIBGDX - SetScreen空指針異常

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

在你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中,您正在嘗試使用不存在的遊戲。你需要使用「這個」你GameScreen通過TypingGame的實例,並將其存儲在:

TypingGame game; 
您GameScreen的

另外,作爲一個側面說明(但很重要!),要創建GameScreen的一個實例,GameOverScreen的實例,但後來每次你設置你創建一個新的屏幕時間...

+0

完美的我知道了,非常感謝。 – user2649458

0

而且,爲什麼要創建一個新的gameScreen然後不使用它在setScreen()

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

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

我預計最後一行寫着:setScreen(gameScreen);