[SOLVED] The first guess is duplicated on Start()

Hello guys, my first time here. Sorry for my english!

I noticed on my game that sometimes it was setting the first limite after the inicial guess in a wrong way. For exemple:
The game asks at begining if the number was 361; I press Lower; and the game asks if it is 545!?!
I noticed that it is happening only with the first guess.

So I put some “print” statements on the console showing the current value of the variables max, min, and guess to figure out what was going on. I found out the at the Start function, the game is modifying the variable guess 2 times. It is using the first value to make the limite, and displaying the second value on UI Text. Here a print of the exemple above:

You can replicate the logs on your game by adding this lines on the NextGuess() function:
void NextGuess () {
guess = Random.Range(min,max+1);
text.text = guess.ToString()+"?";
maxGuesses=maxGuesses-1;
if(maxGuesses<=0){
Application.LoadLevel(“Win”);
}
print ("guess = "+guess);
print ("max = "+max);
print ("min = "+min);
}

I had a similar problem, and I managed to solve it, probably I’ll be able to help you.

I guess that, in the NumberWizard script, you have 4 methods: Start, GuessHigher, GuessLower and NextGuess.

NextGuess code is ok (protip: to increase o decrease by 1 the value of a variable, you can use respectively [varname]++; or [varname]–; it’s faster to type :wink: ).

The Start method should look something like this:
void Start () {
NextGuess();
}

Now, if it looks like mine, then you should check why the Start method is executed more than once (it should only be executed exactly once in the Game scene). Follow these steps:

  • Double click on all your Scenes one by one
  • Click once on every object that you have in Hierarchy (and I mean all of them, even Main Cameras, Canvases, etc.)
  • Look at the Inspector panel of each object, and check if there’s a Script component of NumberWizard.cs active (edit: you can use the Find instrument in the Hierarchy of each Scene and search for NumberWizard, if there’re components with that name in any object of the selected Scene you’ll get them in the Hierarchy, it’s quicker this way)
  • If there is, remove it.

The only place where there should be a NumberWizard.cs script component, is in the NumberWizard object under Main Camera in the Game scene.

Most probably you’ll have another script component elsewhere, which tells Unity to execute the script more than once, thus creating the problem that you described (modifying guess twice).

Hope this helps!

2 Likes

You Rock! Thank you very much!

The NumberWizard.cs script was showing in the Number Wizard (Game Object) and in the Guess (Game Object). I must have understood something wrong when tried to modify the Guess Object with the Number Wizard script.

Privacy & Terms