简介: 我正在构建一个游戏,怪物在顶部生成,并通过路径移动,到达需要移除/摧毁/删除它们的点。但我似乎无法删除怪物对象。
for (Monster i : Monstre)
{
this.add(i); //adds monster to JPanel
if(i.monstery > 50 && i.monsterx > 50){ //check if monster have reached end point
this.remove(i); //Should remove Object from the JPanel ?
i = null; //Sets object too null
Monstre.remove(i); //Removes object from arrayList "Monstre".
}else{
//Update the monsters bounds
上面从 JPanel 中删除了对象,看起来一切正常。但是当我调用 System.out.println(Monstre.size());
时,我得到越来越多的怪物生成,如果增加怪物生成率,程序最终会开始变慢,因为Monstre 数组列表中的怪物数量超过 9000,并且从未减少。
我正在寻找的是一种在游戏运行时删除这些对象的方法。
最佳答案
删除 i = null;
行。这不是 C,您不必将变量分配给 null
。 JVM 会为你做这件事(谷歌“java garbage collection”)。由于该行,您实际上调用了不起作用的 Monstre.remove(null)
。
此外,您不能以这种方式遍历集合并修改它(删除值)。将要删除的怪物保存在循环范围之外的数组中,并在循环结束后将其删除。否则,使用迭代器:
Iterator<Monster> it= Monstre.iterator();
while (it.hasNext()) {
Monster i= it.next();
//code code code
if (shouldDelete) {
this.remove(i);
it.remove();
}
}
关于java - 怪物对象删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16522831/