If statement inside if statement

Hello everyone .

Plz check the code here for some reason mono is not reading the if statement line 22, and i couldnt figure it out.

the problem is in this line ==> if (Input.GetKeyDown(KeyCode.Y)

Here is the code .

using UnityEngine;
using System.Collections;

public class Numberwizard : MonoBehaviour {

int min = 1 ;
int max = 1001 ;
int guess = 500 ;
// Use this for initialization
void Start () {
NumberWizard();
}

// Update is called once per frame
void Update () {

  if (Input.GetKeyDown (KeyCode.Return)) {
  	/*print ("the number is " + guess ");
  	print ("I won ");
  	print ("==========================================");
  	print ("Do you want to restart?");
  	print ("'Y'for yes and 'N' for no");*/
  	if (Input.GetKeyDown(KeyCode.Y)){
  		print("ok");
  	}
  }else if (Input.GetKeyDown (KeyCode.UpArrow)) {
          print ("Your number is higher than " + guess );
  	      min = guess; 
  	      guess = (min + max) / 2;
     } else if (Input.GetKeyDown (KeyCode.DownArrow)) {
         	print ("the number is lower than " + guess + ");
  	        max = guess; 
  	        guess = (max + min) / 2; 
     }
 }

void NumberWizard(){

  print ("Welcome to number wizard ");
  print ("Try to guess the number ");
  print ("guess a number between 1 and 1000  ");
  print ("is your guess higher than 500 or lower ?");

}
}

Hi,

When you say “Mono isn’t reading the line” do you mean that bit of the code just isn’t working?

Assuming so, here’s why…

The Update method is being called every frame. You have one if statement that is effectively saying “has the return key been pressed down in this frame”, you are then asking “has the Y key been pressed down in this frame”.

It comes down to you not being able to press both keys at the same time quickly enough.

In order to resolve this you would need to introduce some form of state to remember that Return had been pressed, and then if it has, run the check for the Y key.

You could use a boolean to store whether Return has been pressed, but remember, you need to reset it after the end result, otherwise next time it runs it’s going to think that the Return is still pressed, when it isn’t.

Why do you want that test for Return in the first place?


See also;

1 Like

Privacy & Terms