我是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);"
导致空点异常,即使所有内容都是初始化的。评论此行后,一切正常,但显示没有精灵。
这里是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;
}
答案 0 :(得分:4)
您尚未初始化mMainScene。您无法参考(即在您定义了mMainScene之前附加儿童/呼叫方法。)
您可以检查mMainScene是否为空,或者将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());
}