Gin*_*as_ 3 java arrays null reference object
我在GameWorld中有一系列游戏对象,他们可以从那个世界中删除.问题是某些游戏对象引用了其他游戏对象.例如,Player类引用了Bird.Bird会从GameWorld中随机删除,但Player仍然会引用它.我目前进行空检查以检查GameObject是否仍然有效并且在世界上.但是,从数组中删除对象不会使该引用为null.那我怎么能把它变成空?
这是一个例子:
// 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
Run Code Online (Sandbox Code Playgroud)
你不能制作一个对象 null,你只能做一个参考null.更新对象的一个引用不会更改对同一对象的其他引用.
想想它就像我们在手机中拥有相同人的号码一样:如果删除号码,它就不会从手机中删除.如果我们都删除它,那个人的电话号码就不会停止存在:我们都不能打电话给他们.
你唯一能做的就是:
referencedBird = null明确设定;gameObjects.get(0)通过referencedBird变量引用它而不是变量.| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |