I’ve seen the Shuffle examples mostly in C#, but I am curious to see a Fisher-Yates written in UnityScript. I looked at how it is written in Javascript, but it doesn’t translate well in UnityScript.
I used an example of the Shuffle from [Mike Bostock’s website][1]
Here is my attempt:
function shuffleThis(myArray)
{
var m = myArray.length;
// While there remain elements to shuffle…
while (m)
{
// Pick a remaining element…
var i = Mathf.Floor((Random.Range(0, myArray.length)) * m--);
// And swap it with the current element.
var t = myArray[m];
myArray[m] = myArray*;*
myArray = t; }
return myArray; } I want to shuffle through 4 numbers (1-4) var groupSelect = [1,2,3,4];
shuffleThis(groupSelect);
print(shuffleThis(groupSelect); However, I get a few errors about ‘length’ is not an member of ‘Object’ and things start to fall apart fast.
You need to define types always, either by supplying a value or specifying the type, the latter of which is necessary in the case of function definitions. Also the convention in Unity is lowercase for variables and uppercase for methods and classes; follow this since it makes everything consistent and easier to follow.
function ShuffleThis (myArray : Array)
However you should not actually use the Array class, since it’s slow and obsolete. Use built-in arrays if the array is a fixed size (i.e., int), or generic Lists (i.e., List.< int >) if you need to add/remove elements from the array easily.
Alright, so I forgot where exactly I saw this, but I found something that was similar to what I needed for a Fisher-Yates shuffle. I modified it slightly since I wanted control over the array before I plug it into a function to handle the rest.
var startingArray = [1,4,5,2,6];
This will be the array I will call to get Shuffled
function ShuffleThis(data : Array) : Array
{
var size : int = data.length;
for (var i : int = 0; i < size; i++)
{
var indexToSwap : int = Random.Range(i, size);
var oldValue = data*;*
data = data[indexToSwap]; data[indexToSwap] = oldValue; } return data; } Then I call the function to shuffle the array var. var pickElement = ShuffleThis(startingArray); pickElement.pop()//Picks the last element of the array that was just Shuffled. You can create a loop to keep calling pickElement.pop() to go down the shuffled array from last element to the first. This method works for what I need, and maybe it can work for you.