【发布时间】:2016-10-26 16:03:46
【问题描述】:
在我的 Game World 类中,我希望有一个数组,其中包含使用名为 Fighters 的超级类的所有敌人。
public Array<Fighters> enemies;
我在我的游戏世界的构造函数中初始化它。
enemies = new Array<Fighters>();
这是超级战士类。
public class Fighters {
protected Vector3 position;
protected Vector3 velocity;
protected Texture texture;
public Vector3 getPos() {
return position;
}
public Vector3 getVelocity() {
return velocity;
}
public Texture getTexture() {
return texture;
}
public void setPos(Vector3 newPos) {
position = newPos;
}
}
还有一个是 Fighters 子类的类。
public class RedFighter extends Fighters {
public static final int value = 1;
public RedFighter() {
position = new Vector3(-10, -10, 0);
velocity = new Vector3(0, -10, 0);
texture = new Texture("redfighter.png");
}
}
当我调用一个名为 spawn faces 的方法时,它应该用 redfighters 填充数组。但是,当我尝试添加它时,我不断收到 NullPointException。
Fighters fighter;
fighter = new RedFighter();
enemies.add(fighter);
我做错了什么,我该如何解决?谢谢!
【问题讨论】:
-
你的 Fighters 构造函数在哪里,你在哪里分配它的类变量?
-
我不想真正制作 Fighters 的对象,所以我没有包含构造函数。它最初是一个抽象类,但为了解决这个问题,我删除了它。
-
如果在调用
enemies.add(fighter);时得到NPE,那是因为enemies仍然为空。此外,在 RedFighter 类中加载纹理不是一个好主意,否则游戏将不得不无缘无故地多次加载相同的纹理。 -
啊...你是完全正确的持有不持有纹理。我会解决的。
-
能否请您显示堆栈跟踪?另外,你从哪里得到 Array 类?
标签: java arrays libgdx superclass