我正在做一个编程入门课程的项目,我遇到了一个小问题。我们在做侧滚轴,我现在正在记分器上工作。我的问题是,当我尝试在act方法以外的任何方法中创建对counter类的引用时(每帧调用一次),我会得到一个空指针异常错误。如果你想看一下,你可以下载包含我的代码的压缩文件here。
编辑:这是有问题的代码:
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);
}}
发布于 2015-01-29 16:39:00
在将自己从世界中移除之后,您将在addScore()中调用getWorld()。在这种情况下,getWorld()将返回null,因此您将得到一个null指针异常。在将自己从世界中删除之前,尝试更改remove()中的顺序以添加分数。
https://stackoverflow.com/questions/28195888
复制相似问题