- Home /
How to change function of a key with a boolean
So I am trying to use a boolean to make it so at one instance the return key does something different than at a different instance.
The return boolean is reset back to "true" once space has been pressed and the game restarts. That much works but when I press enter in the game it goes through both if statements.
bool returnBoolean;
if (Input.GetKeyDown(KeyCode.Return) && returnBool == true) {
print ("Here we go!\n\n" + "Is your number " + guess + " ?");
returnBool = false;
}
if (Input.GetKeyDown(KeyCode.Return) && returnBool == false) {
print("I won!");
print("Press 'Space' to play again!");
}
How do I make it so this boolean can change the function of the key? I don't see where my logic is wrong here.
Answer by Garazbolg · Nov 12, 2015 at 04:58 PM
Your problem is that if returnBool is true it will enter the first block and at the end of it returnBool is changed to false. Then it meets the second if statement and your boolean is set to false so it goes in.
What you need is to use a else if statement like this :
if (Input.GetKeyDown(KeyCode.Return) && returnBool == true) {
print ("Here we go!\n\n" + "Is your number " + guess + " ?");
returnBool = false;
}
else if (Input.GetKeyDown(KeyCode.Return) && returnBool == false) {
print("I won!");
print("Press 'Space' to play again!");
}
So it will only enter the second block if it didn't enter the first.
Hope that helps you.
It would probably be even clearer if you write:
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Return)) {
if (returnBool)
{
print ("Here we go!\n\n" + "Is your number " + guess + " ?");
returnBool = false;
}
else {
print("I won!");
print("Press 'Space' to play again!");
}
}
Your answer
Follow this Question
Related Questions
Need help accessing booleans from other script. 2 Answers
c# Ignoring conditional statement? 1 Answer
How can i reverse all the booleans in a method? 2 Answers
GetComponent, set boolean to true but it willn't revert 3 Answers
What does this mean? 1 Answer