我点击了每一个我能找到的可能对我有帮助但没有成功的谷歌结果。
我已经构建了一个游戏,我想用它来实现一个完整的 UI。在我的游戏中,我的精灵有单独的类,所以在做几个制作屏幕的教程时,我尝试实现一些可以使用这些单独的类来获取纹理、当前帧等的东西。
我已经到了可以在两个屏幕之间切换的地步,如果它们没有引用它们自身之外的任何东西,但是每当我尝试在游戏屏幕上引用我的精灵类时,它就会崩溃,在游戏类中指向我:
if (screen != null) screen.render(Gdx.graphics.getDeltaTime());
所以这是我正在使用的代码(减去任何已实现的方法或其他类默认的东西)。
教程.java:
public class Tutorial extends Game {
MainMenuScreen mainMenuScreen ;
AnotherScreen anotherScreen;
Player player ;
@Override
public void create() {
mainMenuScreen = new MainMenuScreen(this);
anotherScreen = new AnotherScreen(this);
setScreen(mainMenuScreen);
}
}
MainMenuScreen.java(问题在批处理中):
public class MainMenuScreen implements Screen {
Tutorial game ;
SpriteBatch batch ;
Player player ;
Texture test ;
public MainMenuScreen(Tutorial game){
this.game = game;
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(player.playerTexture, 200, 200); // error points to here
batch.end();
}
}
AnotherScreen.java(运行良好):
public class AnotherScreen implements Screen {
Tutorial game ;
SpriteBatch batch ;
Texture test ;
public AnotherScreen(Tutorial game){
this.game = game;
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(test, 0, 200);
batch.end();
}
@Override
public void show() {
batch = new SpriteBatch();
test = new Texture(Gdx.files.internal("badlogic.jpg"));
}
}
播放器.java:
public class Player {
Texture playerTexture ;
Vector2 position;
String textureLoc;
public Player(Vector2 position, String textureLoc){
//What I am trying to get from AnotherScreen.java
playerTexture = new Texture(Gdx.files.internal("badlogic.jpg"));
}
public Texture getPlayerTexture() {
return playerTexture;
}
public void setPlayerTexture(Texture playerTexture) {
this.playerTexture = playerTexture;
}
}
控制台中的确切错误是:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.tutorial.MainMenuScreen.render(MainMenuScreen.java:25)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:206)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
我究竟做错了什么?我重新安排了将所有内容放在不同位置的代码,但我无法让它工作。感谢您的时间!
我发现如果我打开 MainMenuScreen,然后转到 AnotherScreen 并尝试从 Main 获取纹理以显示在 Another 中,如果我让 Tutorial 在将纹理传递给 Another 之前获取纹理,它会起作用。虽然这不适用于播放器...