- Home /
Why doesn't my if statement work?
I'm a little confused as to why my If statement isn't working.
Basically, I have a project set up so that I can open any of 3 scenes from a main menu, and then hit the 'escape' key to return to the main menu. I currently have it working on two of my scenes, but not on the third.
The code I'm adding the return feature to is a coin collector, where the user clicks coins to make them disappear. Here's a snippet from the update function:
public void Update ()
{
if (Input.GetKeyUp(KeyCode.Escape))
{
SceneManager.LoadScene(0);
MenuScript.ReturnOn();
Debug.Log("Escape");
}
if (Input.GetKeyUp (KeyCode.Space))
{
int counter = 0;
while (counter < 100)
{
GameObject myClonedSprite = Instantiate(gameObject) as GameObject;
myClonedSprite.transform.Translate(0.5f, 0.5f, 0);
counter++;
}
}
}
You can see the first 'if' statement is my return to menu. The problem is that when there is a coin (the GameObject in the code) in the scene, the escape key works fine. However, when there isn't a coin, then the escape key does nothing. I feel like it might be some clashing between the if statements, but I've tried replacing the return code, but nothing has worked. I'm fairly new to programming, so excuse my naivety.
There's nothing obviously wrong with your script - the if
statements are completely independent. You can prove this by removing the entire second block (from line 10-22). When you say "the escape key does nothing", you don't get the word "Escape" written to the console log? What does $$anonymous$$enuScript.ReturnOn do?
In the situations where the escape key does nothing, is this script attached to an active object in the scene?
Answer by patrakus · Apr 02, 2017 at 07:25 PM
For me your if statemant are correctly writed, but why do you have public before Update()? Remove this and check if this helped.
This won't solve this problem. $$anonymous$$essage events aren't required to be public due to the way unity invokes them, but setting them to be public doesn't prevent them from working (it just removes some protection and allows them to be called by things that shouldn't be calling them).
Your answer
![](https://koobas.hobune.stream/wayback/20220612114414im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
If statement will not return true 3 Answers
Return Acting As Space(4.3.2) 0 Answers
Using bool function with parameters 1 Answer
My "if" is not working and have no idea why 1 Answer
Time is not stopping 2 Answers