我正在做一个介绍编程课程的项目,但遇到了一个小问题。我们正在制作一个横向卷轴,我现在正在做计分器。我的问题是,当我尝试在 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);
}
}