/// With the Fisher-Yates shuffle, first implemented on computers by Durstenfeld in 1964,
/// we randomly sort elements. This is an accurate, effective shuffling method for all array types.
public static List<GameObject> Fisher_Yates_CardDeck_Shuffle (List<GameObject>aList) {
System.Random _random = new System.Random ();
GameObject myGO;
int n = aList.Count;
for (int i = 0; i < n; i++)
{
// NextDouble returns a random number between 0 and 1.
// ... It is equivalent to Math.random() in Java.
int r = i + (int)(_random.NextDouble() * (n - i));
myGO = aList[r];
aList[r] = aList*;*
I searched for an answer for this myself, and got so aggravated with all the different answers, that I made a clear concise way to do this myself:
public List<float> toShuffle = new List<float>();
public List<float> shuffled = new List<float>();
// ShuffleList(toShuffle);
public void ShuffleList(List<float> list)
{
List<float> temp = new List<float>();
temp.AddRange(list);
for (int i = 0; i < list.Count; i++)
{
int index = Random.Range(0, temp.Count - 1);
shuffled.Add(temp[index]);
temp.RemoveAt(index);
}
}
I am sure this can be refined with more testing, and cooler heads. But this method works perfectly fine, and does exactly what I needed(to shuffle a List).
after a little search this is how I got mine to work…
Maybe it helps somebody else
void Shuffle(List<GameObject> a)
{
// Loop array
for (int i = a.Count - 1; i > 0; i--)
{
// Randomize a number between 0 and i (so that the range decreases each time)
int rnd = UnityEngine.Random.Range(0, i);
// Save the value of the current i, otherwise it'll overwrite when we swap the values
GameObject temp = a*;*
// Swap the new and old values a = a[rnd]; a[rnd] = temp; }
// Print for (int i = 0; i < a.Count; i++) { Debug.Log(a*);* } }
Minor modernisation of the above. Note that I’ve placed this as a static function in its own class for easy access anywhere in the project, and that it uses Generics to accept an array of any kind. This is a shuffle-in-place version of the code, but could easily be adapted to return a new array.
public class Randomise
{
public static void Shuffle<T>(ref T[] array) {
for (int i = array.Length - 1; i > 0; i--) {
var r = UnityEngine.Random.Range(0, i + 1);
if (r == i) continue;
var temp = array[i];
array[i] = array[r];
array[r] = temp;
}
}
}