Skip to content

Instantly share code, notes, and snippets.

@munkbusiness
Created March 20, 2018 10:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save munkbusiness/9223ccbb91835d69cc31f58551ebf8a3 to your computer and use it in GitHub Desktop.
Save munkbusiness/9223ccbb91835d69cc31f58551ebf8a3 to your computer and use it in GitHub Desktop.
Generic type array shuffling based on @fincha solutions
using System.Collections.Generic;
using UnityEngine;
public static class EnumerableExtensions {
public static T[] ShuffleArray<T>(this T[] a) {
// Loops through array
for (int i = a.Length - 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 overright when we swap the values
T temp = a[i];
// Swap the new and old values
a[i] = a[rnd];
a[rnd] = temp;
}
return a;
}
}
@munkbusiness
Copy link
Author

munkbusiness commented Mar 20, 2018

All arrays automatically gets the shuffle method so you can access it on any array by simple calling anyArrayName.ShuffleArray();

Adapted from this gist by @fincha https://gist.github.com/fincha/7770c902b674973353e0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment