Non-repeating random numbers in Unity

Some folks on the Unity forum were discussing non-repeating random number.  One fast and simple technique for this is known as the Knuth-Fisher-Yates Shuffle. Very useful for randomizing arrays of any type.


So I wrote a quick generalized C# template that I use in our code. You can, of course pass in integer arrays, but any other type of array as well. Perhaps, for example, an array of Gamebject prefabs to shuffle the order in which they spawn.

public static void RandomizeArray<T>(T[] array)
    int size = array.Length;
    for (int i=0; i < size; i++)
        int indexToSwap = Random.Range(i, size);
        T swapValue = array[i];
        array[i] = array[indexToSwap];
        array[indexToSwap] = swapValue;
} call it with integers...

// Non repeating random numbers from 0 to count

int[] indexArray = new int[count];
// Fill with sequeential indexes then randomize
for(int i=0; i<indexArray.Length; ++i)
    indexArray[i] = i;
RandomizeArray<int>(indexArray); call it with game object prefabs...

// Non repeating prefab spawn 
public GameObject arrayOfPrefabsToSpawn[]; // An array of the prefabs that should be spawned
RandomizeArray<GameObject >(arrayOfPrefabsToSpawn);
// Now just sequentially instantiate the prefab gameobjects in the arrayOfPrefabsToSpawn as needed.   
// You can, of course, just call RandomizeArray again when the end is reached and start the spawn loop again.
// And, really, for performance, use a spawn pool instead of instantiate!
for(int i=0; i<arrayOfPrefabsToSpawn.Length; ++i)
    yield return new WaitForSeconds(spawnDelay);