About 'Use Random.Range()'!

Same here. This totally works for me too. I am super confused as to why @Rick_Davidson added in the extra check to subtract and add in the OnPressHigher and OnPressLower functions resp all in the name of avoiding repetition. I am thinking if the minimum number was already displayed, the player would have selected it as the correct value and we would not reach this stage. :thinking:

@Rick_Davidson, are we missing something please?

After vigorous testing, this approach indeed includes the Guesses already guessed before. Especially the minimum guesses. You better tripple test it too @bhindi1224.

This comment is probably way out of date, but I thought I’d add it anyway…
You say in the video that because “max” is exclusive in Random.Range, we should put “max + 1”; however, the documentation says that if min=max, the “min” gets returned; so I found the code works if I use Random.Range(min, max).
For example, Random.Range(1000, 1000) will return 1000.

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

public class NumberWizard : MonoBehaviour {

[SerializeField] int max;
[SerializeField] int max_original;
[SerializeField] int min;
[SerializeField] TextMeshProUGUI guessText;
int guess;

// Use this for initialization
void Start ()
{
    StartGame();
}

void StartGame()
{
    NextGuess();
    max = max + 1;
}

public void OnPressHigher()
{
    if((min + 1) < max)
    {
        min = guess + 1;
    }
    else
    {
        min = guess;
    }

    NextGuess();
}

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

void NextGuess()
{
    guess = Random.Range(min, max + 1);

    if (guess > max_original)
    {
        guess = max_original;
    }

    guessText.text = guess.ToString();
}

}

For those, who have problems like “1001”, “1002” and etc., you can just add this:

public void OnPressHigher()
{
    min = Mathf.Min(guess + 1, max);
    NextGuess();
}

public void OnPressLower()
{
    max = Mathf.Max(guess - 1, min);
    NextGuess();
}

This prevents the minimum number to go up higher than the maximum one, and prevents the maximum number to go down lower than the minimum one.

Privacy & Terms