我是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);"导致了空点异常,即使所有内容都初始化了。在评论这一行后,一切工作正常,但显示是没有精灵。
这是Mmainsene被初始化的代码
    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是什么之前,不能引用(即附加子对象/调用方法)。
您可以检查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());
    }

10-04 11:02