我是 Android 游戏开发的新手。我一直在尝试一个游戏开发的例子,但有些无法理解android中空点异常的原因。
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(512, 512,
TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(this.mBitmapTextureAtlas, this, "Player.png",
0, 0);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
final int PlayerX = (int)(mCamera.getWidth() / 2);
final int PlayerY = (int) ((mCamera.getHeight() - mPlayerTextureRegion
.getHeight()) / 2);
this.player = new Sprite(PlayerX, PlayerY, this.mPlayerTextureRegion);
this.player.setScale(2);
this.mMainScene.attachChild(this.player);
}
最后一行“this.mMainScene.attachChild(this.player);”
导致空点异常,即使所有内容都已初始化。评论此行后,一切正常,但显示没有 Sprite 。
这是初始化mMainScene的代码
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mMainScene = new Scene();
this.mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
return mMainScene;
}
最佳答案
您尚未初始化mMainScene。您无法引用(即在定义 mMainScene 之前附加 Children/调用方法。)
您能否检查一下 mMainScene 是否为 null,或者将 mMainScene 的分配移至 onLoadResources() 中?
能否将 mMainScene 定义从 onLoadScene 移至 onLoadResources 中?
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(512, 512,
TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory
.createFromAsset(this.mBitmapTextureAtlas, this, "Player.png",
0, 0);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
final int PlayerX = (int)(mCamera.getWidth() / 2);
final int PlayerY = (int) ((mCamera.getHeight() - mPlayerTextureRegion
.getHeight()) / 2);
this.player = new Sprite(PlayerX, PlayerY, this.mPlayerTextureRegion);
this.player.setScale(2);
this.mMainScene = new Scene();
this.mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
this.mMainScene.attachChild(this.player);
}
public Scene onLoadScene() {
return mMainScene;
}
编辑:
基于 Snake 的示例看来您应该在 onLoadScene 方法中将子项添加到场景中:
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mScene = new Scene();
for(int i = 0; i < LAYER_COUNT; i++) {
this.mScene.attachChild(new Entity());
}
关于java - android中出现NullPointerException的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8305322/