Number Wizard Guess is OVER 1,000

Okay so Dragon Ball reference aside, I had a go with the number wizard UI recently, and I seem to not be able to understand the random inclusion. My random variable can go above 1000 (between 1000 and 1004). My values are as follows:

Min is: 1
Max is: 1000

Code is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class NumberWizard : MonoBehaviour
{

// Initialiase varialbles
[SerializeField] int max;
[SerializeField] int min;
[SerializeField] TextMeshProUGUI guessText;

int guess;

// Start is called before the first frame update
void Start()
{
    StartGame();
}

//new Function to start a game
void StartGame() {

    nextGuess();
    //max += 1;
}



public void OnPressHigher() {
    min = guess +1;
    nextGuess();
}

public void OnPressLower() {
    max = guess -1;
    nextGuess();
}

void nextGuess() {
    //guess = (max+min)/2;
    guess = Random.Range(min, max+1);
    guessText.text = guess.ToString();
}
}

Thanks for the help!

Just to add onto the above, I get to 1000, but if I keep pressing up, I can get to 1001, 1002, 1004, and thats the highest. I think in the video it shows it stops at 1000?

Not sure if its the correct solution, but I guess I found a work around where I used a ternary operator to test for the 1000 value:

min = guess +1;

to

min = guess + 1 >= 1000 ? 1000 : guess + 1;

Guess you could use an if statement instead.

I’m guessing the error comes up because my guess value is 1000, but I’m still adding 1 to min and the Random.Range will just flip my min/max values to low/high, so its still increasing between (1000 and 10001), though its odd that it only goes to 1004 lol.

The reason your code isn’t quite working is because your min value can go up, but if you keep going to guess higher, the max value won’t change so it will cap once the min and the max are the same. It will go up a few numbers past the max since you are adding “+1” to it, and then it won’t budge once the min can no longer be increased. Test it out by setting your min and max to say, 1 and 10 and you’ll get the same effect.

In the number wizard code, the “Next Guess” code is:

guess = (max + min) / 2;

Which is probably a better way to create a new guess and it won’t allow for the max to increase if you don’t need it to (like when you’re guessing higher).

Your solution can work though - if want to simply just write that logic to cap the number. You can also use things like Mathf.Clamp – which can be used to ensure a number generated never goes over what you set the max to!

Has your question been answered, @trustnoone?


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms