Skip to content

Instantly share code, notes, and snippets.

@cosmicmonster
Last active March 1, 2021 13:36
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cosmicmonster/7393396 to your computer and use it in GitHub Desktop.
Save cosmicmonster/7393396 to your computer and use it in GitHub Desktop.
Unity / C# code to shuffle an array using the Fisher-Yates Shuffle.
using UnityEngine;
using System.Collections;
public class ShuffleArray : MonoBehaviour {
// Public so you can fill the array in the inspector
public int[] scenarios;
void Start ()
{
// Shuffle scenarios array
Shuffle (scenarios);
}
void Shuffle(int[] a)
{
// Loops through array backwards
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 = Random.Range(0,i);
// Save the value of the current i, otherwise it'll overright when we swap the values
int temp = a[i];
// Swap the new and old values
a[i] = a[rnd];
a[rnd] = temp;
}
// Check your output
for (int i = 0; i < a.Length; i++)
{
Debug.Log (a[i]);
}
}
}
@exgebv
Copy link

exgebv commented Feb 12, 2019

where I should put this script?
on the object? on main camera? else?

@LockerSmith
Copy link

Thanks man. That's what I need.

@lenetid
Copy link

lenetid commented Aug 2, 2019

hmm

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