我在 GameWorld 中有一系列游戏对象,它们可以从那个世界中移除。问题是某些游戏对象引用了其他游戏对象。例如。 Player 类有一个对 Bird 的引用。 Bird 被随机从 GameWorld 中移除,但 Player 仍然有对它的引用。我目前做一个空检查来检查游戏对象是否仍然有效并且在世界上。但是,从数组中删除对象不会使该引用为空。那么我怎样才能让它为空呢?
这是一个例子:
// GameWorld creates bird
ArrayList<Object> gameObjects = new ArrayList<>();
Object bird = new Object();
gameObjects.add(bird);
// Player references it
Object referencedBird = gameObjects.get(0);
// later in GameWorld, another scope, there is no access to the 'bird' object, trying to remove the bird from the world
Object objectToRemove = gameObjects.get(0);
gameObjects.remove(0);
objectToRemove = null;
// back in the Player class
Debug.log("is null " + (referencedBird == null)); // false! I need it to be true
最佳答案
你不能让一个对象null
,你只能让一个引用null
。更新对对象的一个引用不会更改对同一对象的其他引用。
想一想我们的手机中都有同一个人的号码:如果我删除该号码,它不会从您的手机中删除。如果我们都删除它,那个人的电话号码不会不复存在:只是我们都不能调用他们。
你唯一能做的是:
- 明确设置
referencedBird = null
; - 或者通过
gameObjects.get(0)
而不是通过referencedBird
变量来引用它。
关于java - 如何通过仅在数组中引用来使对象为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38570436/