[SOLVED] Code now no longer waits for input

I was almost done with the number wizard, I changed the code, (but I don’t know how and now when I press play in Unity 4.7.2 I get a runaway loop. As you can see in the picture.

I uploaded my code to github NumberWizard.cs

I’ve tried to look at the completed code on undemy and it looks the same to me, I tried checking for any missing semicolons, I made sure the code was compiling correctly.

Thanks in advance.

1 Like

Hello @shifteight,

At a glance I believe it’s this;

void Update () {

  if (Input.GetKeyDown(KeyCode.UpArrow)){
  	minimum = guess;
  	NextGuess ();
  } else if (Input.GetKeyDown(KeyCode.DownArrow)){
  	maximum = guess;
  	NextGuess ();
  } else if (Input.GetKeyDown(KeyCode.Return)){
  	print("I won!");}
  	StartGame();

}

If you look carefully after your last else if you will notice a closing bracket after the print("I wont!"); statement.

You then call StartGame(); but because this is now outside of the logic block it is being call every time regardless of the input from the user, thus, every frame.

Sometimes it’s easier to lay out the if statements slightly differently just to make them a little more readable, at least at first, for example;

void Update () {
	
    if (Input.GetKeyDown(KeyCode.UpArrow))
        {
	    minimum = guess;
	    NextGuess ();
        } 
    else if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            maximum = guess;
            NextGuess ();
        } 
    else if (Input.GetKeyDown(KeyCode.Return))
        {
	    print("I won!");}    // NOTE: Now you can see this bracket more easily
	    StartGame();
                                     // NOTE: Now you can see there is one missing
}

Obviously once it’s all checked you can put it back to how you want, another tip is to create the methods and code blocks with their structure first, e.g;

void myMethod() {

}

This one is now ready for some code to go in the middle, or;

void myMethod() {
    if () {
        
    }
}

The one above is now ready for the condition for the if statement and what to do if the test is true. You will most likely see some temporary error messages with the latter example as it will be expecting something in the () brackets for the if statement, but it gives you an opportunity to set the structure of your code blocks whilst you are getting the hang of things.

Hope this helps.

2 Likes

Rob,

Thanks for the input, and I’m going to start creating the code blocks when I 1st create methods.

Thanks!

1 Like

You already are! :slight_smile:

1 Like

Privacy & Terms