非空对象上的空指针取消引用异常

Null pointer dereference exception on non-null object

我正在使用 libGDX 1.5.6 和 Android Studio 1.1.0。我想要一个 activity 向用户显示一个 ApplicationListener(最终以 3d space 渲染模型并用相机查看它们)。

我有一个 Android 应用程序可以在活动之间成功切换(超级简单)。然后我用本教程中的 libGDX 启动逻辑交换了 onCreate 方法中的逻辑(activity 被切换到):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());
}

有人看到我明显遗漏了什么吗?

modelBatch 尚未实例化。

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