我创建了一个名为endGame的布尔值,当我单击一个按钮时,它将被设置为false
,然后在另一个类上,我为我的布尔值所在的类创建了一个对象。当发生某些事情时,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);
}
答案 0 :(得分:1)
然后在另一个类上我为我的布尔值为
的类创建了一个对象
我认为endGame
变量不是静态的。否则,您不需要创建布尔值的类的对象来访问它。
这意味着如果您在相关类的一个对象中将endGame
设置为true,则不会在该类的不同对象中更新endGame
的值。
答案 1 :(得分:0)
你有几种方法可以解决这个问题,也许我会说这不是最好的,但不知道他们的代码是什么。因为如果这些类没有相互继承,或者你可以使用单例模式?,我认为这个例子对你的观察者来说可能是值得的:
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;
}
}
在您的代码中,例如,这是一个伪代码,您在您需要的类中实现EndGameOBJ ,您可以在公共类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);
}
我希望它对我的英语有帮助并道歉。