问题
I know I have asked this question so similar before but I get there no more answer ... I would like, as soon as I lost in my game, my HighScore displayed. Here is the code:
protected Preferences HighScore () {
if (score > highscore) {
prefs.putInteger("highscore", score);
this.highscore = prefs.getInteger("highscore", 0);
prefs.flush();
}
return prefs;
}
But if I run my application, only this error is displayed:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at de.firstdemo.game.states.PlayState.HighScore(PlayState.java:641)
at de.firstdemo.game.states.PlayState.render(PlayState.java:601)
at de.firstdemo.game.states.GameStateManager.render(GameStateManager.java:50)
at de.firstdemo.game.RiskyDemo.render(RiskyDemo.java:37)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:225)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)
I looked in the web but couldn't find any solution...
Thanks for your answers! :)
回答1:
First you get the object:
Preferences preferences = Gdx.app.getPreferences("My preferences");
Then, when you lose in your game, you get the value. I usually check if I lose in the render method with a boolean. In this case you compare your highscore with your current score:
if(IsGameFinished)
{
int highscore = preferences.getInteger("High score",0);
if(highscore>=yourCurrentScore)
{
// display highscore
}
else
{
// display yourCurrentScore
preferences.putInteger("High score", yourCurrentScore);
preferences.flush();
}
}
Furthermore in your code there is an error:
protected Preferences HighScore () {
if (score > highscore) {
prefs.putInteger("highscore", score);
prefs.flush(); // YOU SHOULD FLUSH BEFORE!
this.highscore = prefs.getInteger("highscore", 0);
}
return prefs;
}
And, why do you return the Preferences? Returning your highscore as an int should be better.
来源:https://stackoverflow.com/questions/46840077/libgdx-using-preferences-for-highscore