Not repeat random number (Random.Range)

Hello, how can I prevent from a same random number? thanks :slight_smile:

You could store the used values in a list or array, then check against it before using the random value.

Ex:

List<int> usedValues = new List<int>();
public int UniqueRandomInt(int min, int max)
{
	int val = Random.Range(min, max);
	while(usedValues.Contains(val))
	{
		val = Random.Range(min, max);
	}
	return val;
}

private static int lastRandomNumber;

public static int generateRandomNumber(int min, int max) {

    int result = Random.Range(min, max);

    if(result == lastRandomNumber) {

            return generateRandomNumber(min, max);

    }
     
    lastRandomNumber = result;
    return result;

}

Hope this helped you,
Romejanic

In order to never get twice the same value, you need to first store them and remove as you get them:

int [] array = new int[]{0,1,2,3,4,5,6};
List<int>list = null;
void Start(){
    list.AddRange(array);
}

int GetUniqueRandom(bool reloadEmptyList){
     if(list.Count == 0 ){
         if(reloadEmptyList){
             list.AddRange(array); 
         }
         else{
             return -1; // here is up to you 
        }
    }
   int rand = Random.Range(0, list.Count);
   int value = list[rand];
   list.RemoveAt(rand);
   return value;
}

var newRandomNummer : float;
var lastRandomNumber : float;
var min : float;
var max : float;

function MakeRandomNumber() {
newRandomNummer = Random.Range(min,max);
	if(newRandomNummer != lastRandomNumber){
		print(newRandomNummer);
	}
	else{
	//retry!
	}	
}

That could work.

you could use recursive functuion try this

float RandomNum(float lastRandNum)
    {

        float randNum = Random.Range(min, max);
        if (randNum == lastRandNum)
        {
            return RandomNUm(randNum);
        }
        else
        {
            return randNum;
        }
    }

I created an extension for Lists that would make this task really simple:

    /*
     * Shuffle the content of a list
     */
    public static List<T> _Shuffle<T>(this List<T> sourceList)
    {
        List<T> randomizedList = new List<T>();
        List<T> copyList = sourceList.ToList();

        for (int i = 0; i < sourceList.Count; i++)
        {
            int index = Random.Range(0, copyList.Count);
            T randomValue = copyList[index];
            randomizedList.Add(randomValue);
            copyList.Remove(randomValue);
        }

        return randomizedList;
    }

Then just call it on your code

randomBlock = sequentialBlock._Shuffle();

Hope it helps

Hi, guys! Just want to let you know: I created utility to easely handle random without repetitions, flat distributed random, and weighted lists (universal property drawer included!). You can find it on GtiHub and use freely: