2015-07-03 68 views
0

我做了一个叫做endGame的布尔值,当我点击一个按钮时,它将被设置为false,然后在另一个类上为我的布尔所在的类创建了一个对象。而当事情发生在最后阶段将被设置为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

你确定它是classobj的同一个实例吗?你确定你正在通过把变量设置为true的颂歌吗? –

+0

精心制作.......... – Elltz

+0

你在哪里做classObj?这是一个全局变量吗?给我们一些工作在这里! –

回答

1

,然后在另一个类我做了一个对象在我的布尔是

类我假设endGame变量不静态的。否则,您将不需要创建布尔值所在的类的对象以便访问它。

这意味着,如果你在相关类的一个对象设置endGame为true,就不会更新endGame在类的不同对象的价值。

+0

所以我应该把它设置为静态? –

+0

@StormAsdg如果不了解你的应用程序,这很难说。它应该是静态的,或者(如果它不是静态的)所有访问此布尔值的对象都应该使用相关类的同一对象来访问它(这样它们都将看到相同的布尔值)。 – Eran

+0

@StormAsdg我建议你阅读一本关于Java的书。如果没有对类是什么基本的理解,你真的会努力用Java来制作游戏。 – Tenfour04

0

你有几种方法来解决这个问题,也许我会说这不是最好的,但是不知道他们的代码。 ?因为如果类不相互继承,也可以使用Singleton模式,我觉得这个例子可能是值得的,你观察员:

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); 
} 

我希望这会对我的英语有所帮助和道歉。

相关问题