为什么我的布尔变量没有在其他 类 上更新?

Why my boolean variable doesn't get updated on other classes?

我创建了一个名为 endGame 的布尔值,当我单击一个按钮时,它将设置为 false,然后在另一个 class 上,我为 class 创建了一个对象,其中我的布尔值是。当发生某些事情时,endGame 将被设置为 true:

if(condition==true){ //the endGame variable will be equal to true only on this class
 classObj.endGame=true;
}

//on the other class where the endGame is Located it is still false.



   //button class
public boolean endGame;
    public void create(){
    endGame=false;

     playButton.addListener(new InputListener(){
               @Override
               public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                   endGame=false;
                   System.out.println(endGame);
                   return super.touchDown(event, x, y, pointer, button);
               }
           });
    }

    //second class
    if(sprite.getY()>=700){
       buttonObj.endGame=true;
       enemyIterator.remove();
       enemies.remove(sprite);
    }

and then on another class I made an object for the class where my boolean is

我假设 endGame 变量不是静态的。否则,您无需创建布尔值所在的 class 的对象即可访问它。

这意味着如果您在相关 class 的一个对象中将 endGame 设置为 true,它不会更新该 [= 的不同对象中 endGame 的值18=].

你有几种方法来解决这个问题,也许我会说这不是最好的,但对他们的代码一无所知。因为如果 classes 不相互继承,或者你可以使用单例模式?,我认为这个例子对你观察者来说可能是值得的:

public class WraControlEndGame {

    private ArrayList<EndGameOBJ> endGameOBJ = new ArrayList<EndGameOBJ>();

    public void addEndGameOBJ(EndGameOBJ actor){
        endGameOBJ.add(actor);
    }

    public void removeEndGameOBJ(EndGameOBJ actor){
        endGameOBJ.remove(actor);
    }

    public void endGameOBJ_ChangeValue(boolean value){

        for(int a = 0; a < endGameOBJ.size(); a++){
            endGameOBJ.get(a).setEndGame(value);
        }

    }
}

.

public interface EndGameOBJ {
    public void setEndGame(boolean value);
    public boolean getEndGame();
}

.

public class YourClassThatNeedEndGameVariable implements EndGameOBJ{
..// other code


private boolean endGame = false;

..// other code Construct ect

    @Override
    public void setEndGame(boolean value) {
        endGame = value;
    }

      @Override
    public boolean getEndGame() {
        return endGame;
    }

}

.

例如,在您的代码中,这是一个伪代码,您 在您需要的 class 中实现 EndGameOBJ,您在 [= 中查看示例32=] class YourClassThatNeedEndGameVariable

someClass buttonObj = new ....;//now this class implements EndGameOBJ
someClass classObj  = new ....;//now this class implements EndGameOBJ

WraControlEndGame wraControlEndGame = new WraControlEndGame();

wraControlEndGame.addEndGameOBJ(buttonObj);
wraControlEndGame.addEndGameOBJ(classObj);

//bla bla bla



if(condition){

    wraControlEndGame.endGameOBJ_ChangeValue(true);
}

希望对我有所帮助,为我的英语道歉。