0

我正在做一个介绍编程课程的项目,但遇到了一个小问题。我们正在制作一个横向卷轴,我现在正在做计分器。我的问题是,当我尝试在 act 方法(每帧调用一次)之外的任何方法中创建对计数器类的引用时,我得到一个空指针异常错误。如果你想看一下,你可以在这里下载包含我的代码的 zip 文件。

编辑:这是有问题的代码:

public class HeroMissile extends Missiles

{

/**
 * Act - do whatever the HeroMissile wants to do. This method is called whenever
 * the 'Act' or 'Run' button gets pressed in the environment.
 */
public void act() 
{
    move(8);
    remove();
}    

public void remove() {
    if(isTouching(Drone.class)) {
        removeTouching(Drone.class);
        getWorld().addObject(new Explosion(), getX(), getY());
        getWorld().removeObject(this);
        addScore();
        return;
    }
}

public void addScore() {
    City cityWorld = (City) getWorld();
    **Counter scoreCounter = cityWorld.getCounter();**
    scoreCounter.add(1);
}

}

4

1 回答 1

0

在您将自己从世界上移除后,您正在调用getWorld()[in ]。addScore()在这种情况下,getWorld()会返回null,所以你会得到一个空指针异常。尝试更改顺序remove()以添加分数,然后再将自己从世界上移除。

于 2015-01-29T08:39:00.387 回答