2015-07-03 65 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); 
} 

我希望這會對我的英語有所幫助和道歉。

相關問題