Give items unique random numbers

Is there some easy way to give a list of items random numbers, but not the same number twice?

In the Random.Range can we only set min and max value but not exceptions

Just to be clear

for (int i = 0; i < 3; i++) {
    item[i] = Random.Range(0, 3);
}

Like this but with unique numbers on every item.

Maybe something like this:

float newValue = 0;
int itemCount = 0

while (itemCount < 3)
{
   newValue = Random.Range(0, 3);
   if (Array.IndexOf(item, newValue) < 0)
   {
      item[itemCount] = newValue;
      itemCount++;    
   }
}
1 Like
System.Guid myGUID = System.Guid.NewGuid();
3 Likes

You can make a list of numbers in a pool, then assign and remove them at random. You’ll need import System.collections.generic; to use a list. This will work, if you have a pool of numbers in mind that you want to use.

List<int> pool = new List<int>();
for(int i = 0;i < 30;i++)
{
    pool.add(i);
}

for(int i = 0;i < item.Length;i++)
{
    item[i] = pool[Random.Range(0, pool.Count)];
    pool.RemoveAt(i);
}
1 Like

This is the answer.

yes, it is (after reading the msdn, I learned something! thank you)
Tomnnns example is a great gateway to pools, shuffling, etc

Just a short note about Tomnnns code:
If you delete items from a list I would recommend to do this from the upper end to the lower end otherwise it’s possible to run into an AV (as soon as i is larger than the rest size of the list).

for(int i = item.Length;i > 0;i--)
{
    item[item.Length - (item.Length - i)] = pool[Random.Range(0, pool.Count)];
    pool.RemoveAt(i);
}

Beside of this it just reduces the likeliness for duplicate values, but does not avoid it for sure.

A few honorable mentions, woo :smile:

I’m glad nobody mentioned the slow, sometimes incomplete method of checking for duplicated and trying to re-randomize the duplicate indices.