非空对象上的空指针解除引用异常

时间:2015-04-21 04:03:28

标签: java android libgdx

我正在使用libGDX 1.5.6和Android Studio 1.1.0。我希望有一个活动向用户显示ApplicationListener(最终在3d空间中渲染模型并使用相机查看它们)。

我有一个成功切换活动的Android应用程序(超级简单)。然后我用本教程中的libGDX启动逻辑交换了onCreate方法(切换到的活动)中的逻辑:http://steigert.blogspot.com/2012/02/1-libgdx-tutorial-introduction.html

我自己完成了许多构建错误,遇到了一个让我感到困惑的错误:     尝试在空对象引用上调用虚方法'void com.badlogic.gdx.graphics.g3d.ModelBatch.begin(com.badlogic.gdx.graphics.Camera)(在com.example处。 matthew.constellate.Stargazer.render(Stargazer.java:53))

显然有些人认为我的相机是空的,但基于这个来源,我看不出这是怎么可能的:

public class Stargazer implements ApplicationListener
{
public Model model;
public PerspectiveCamera cam;
public ModelInstance instance;
public ModelBatch modelBatch;

@Override
public void create()
{
    // Need a camera
    cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    cam.position.set(0f, 0f, 0f);
    cam.near = 1f;
    cam.far = 300f;
    cam.update();

    // Create obj to test rendering
    ModelBuilder modelBuilder = new ModelBuilder();

    model = modelBuilder.createBox(5f, 5f, 5f,
            new Material(ColorAttribute.createDiffuse(Color.RED)),
            VertexAttributes.Usage.Position |     VertexAttributes.Usage.Normal);

    instance = new ModelInstance(model);
}

@Override
public void render()
{
    Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(),     Gdx.graphics.getHeight());
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

    modelBatch.begin(cam); // LINE 53
    modelBatch.render(instance);
    modelBatch.end();
}

...

正在使用此启动器触发:

protected void onCreate(Bundle savedInstanceState)
{
    boolean useOpenGLES2 = false;

    super.onCreate(savedInstanceState);
    initialize(new Stargazer());
}

有没有人看到我遗失的明显事物?

2 个答案:

答案 0 :(得分:4)

modelBatch尚未实例化。

答案 1 :(得分:0)

我建议在cam方法中添加render对象。