Shuffling/Randomizing a GameObject Array[]...

I have an array of GameObjects here which I would like to shuffle…

var bloxes : GameObject[ ];
//The size of array and its content was then adjusted in the Unity editor later on… and there’s about 8 prefabs in this array.

I follow a tips on randomizing an Array over at Unity Answers… and below is how the overall things looks like:

var bloxes : GameObject[];

function Start() {
	bloxes = RandomizeArray(bloxes);
}

function RandomizeArray(arr) {
	for (var i = arr.length - 1; i > 0; i--) {
		var r = Random.Range(0, i);
		var tmp = arr[i];
		arr[i] = arr[r];
		arr[r] = tmp;
	}
}

So what happen here is that, right after I click play, it gave an error saying:

Assets/My Scripts/SunBloxesMain.js(20,32): BCE0022: Cannot convert 'void' to 'UnityEngine.GameObject[]'.

Can anyone help me out here?

1 Like

You forget to use return, to return the array.

you don’t need to return it, since the array is passed as a pointer. I think you need to specify the parameter type as an array of gameobject though:

function RandomizeArray(arr : GameObject[]) {
	for (var i = arr.length - 1; i > 0; i--) {
		var r = Random.Range(0, i);
		var tmp = arr[i];
		arr[i] = arr[r];
		arr[r] = tmp;
	}
}

Also, that method is altering the array, not creating/returning a new one, so you may be better off not returning a value at all to avoid confusion later:

function Start() {
	RandomizeArray(bloxes);
}

EDIT: ivkoni beat me.