Reputation: 3
I'm mostly following a Udemy course for Unity in which the first game is based solely on the console, where the program attempts to guess the number you think of. My first problem is that, when using Random.Range, it will start with a random number, but pressing the up arrow will first revert it to a lower number, and then increase it on the next presses. The next problem is that pressing the down arrow will always set the number to 1, and it will not increase after that.
using UnityEngine;
using System.Collections;
public class NumberWizard : MonoBehaviour {
int min = 1;
int max = 1000;
int randomGuess;
// Use this for initialization
void Start () {
int randomGuess = Random.Range (min, max);
print ("Welcome to Number Wizard!");
print ("Pick a number between " + min + " and " + max + ".");
print ("Is the number higher or lower than " + randomGuess + "?");
print ("Press up for higher, down for lower, and return for equals.");
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.UpArrow)) {
print ("Up arrow pressed");
min = randomGuess;
randomGuess = Random.Range (min, max);
print ("Higher or lower than " + randomGuess + "?");
}
if (Input.GetKeyDown (KeyCode.DownArrow)) {
print ("Down arrow pressed");
max = randomGuess;
randomGuess = Random.Range (min, max);
print ("Higher or lower than " + randomGuess + "?");
}
if (Input.GetKeyDown (KeyCode.Return)) {
print ("I win");
}
}
}
Upvotes: 0
Views: 216
Reputation: 236248
In Start method you are assigning ranom number to local variable which has same name as class field:
int randomGuess = Random.Range (min, max);
That does not change class field value. I.e. field will stay with default value equal to 0. In Update part you are assigning this 0 either to min or to max field. That's why you stick after pressing Down arrow - all further randoms are generated in range (1, 0). You should assign random number to class field
randomGuess = Random.Range (min, max);
Upvotes: 1