- Home /
Unity UI Button Switch Bool?
I'm trying to get a single UI button to, when pressed the first time, switch a bool from false to true, then the second time switch from true to false, and to be completely honest, i have no idea why it isn't working. Here's the code I've got so far:
void Start () {
chooseConsole = chooseConsole.GetComponent<Button> ();
testConsole = testConsole.GetComponent<Button> ();
testConsole.gameObject.SetActive(false);
chooseConsole.onClick.AddListener(() => { PopDown(); });
}
// Update is called once per frame
void Update () {
if (!Popdown) {
testConsole.gameObject.SetActive (false);
} else {
testConsole.gameObject.SetActive (true);
}
}
public void PopDown() {
if (!Popdown) {
Popdown = true;
} else {
Popdown = false;
}
}
Answer by dazman76 · Jul 04, 2015 at 06:55 PM
There's nothing wrong with this code I'm afraid, at least the part that you've posted. It can be written in a more optimal way, but I have a feeling you've expanded it out to the full IF statements because you were trying to solve the problem. If not, I'm happy to post a simplified and cleaner version - but the code above should definitely result in the Active flag being toggled during Update().
Are you sure you don't have any rogue duplicate copies of the testConsole button, on top of the one you're actually toggling?
Answer by Doodayer · Jul 04, 2015 at 06:10 PM
I figured out the problem. It was this line of code: chooseConsole.onClick.AddListener(() => { PopDown(); });