hi, not sure if i’m right, but i’m guessing that Unity doesn’t support array sort functions like those that you can usually use in JavaScript? i.e.
var mySortedArray : Array = myArray.Sort(function sortByIndex(a, b) { return a - b; });
i get errors if i try this, even if the function is external from the actual Sort arguments. i need to sort an array of arrays by indexing one of the items in each of the arrays contained in the main array (i hope that made sense…), in javascript i thought i could do it like this:
var mySortedArray : Array = myArray.Sort(function sortByIndex(a, b) { return a[1] - b[1]; });
not sure if there’s another way i can do this without sort functions… :?
The .Net Sort function takes an IComparer instance and not an anonymous function, so you will have to do something like this:
class MyComparer extends IComparer {
function Compare (a,b) : int {
return a[1] - b[1];
}
}
And then to sort:
myArray.Sort(new MyComparer());
great, thanks for your help.
i’ve actually come up with a different way of approaching my problem (units in an RTS moving in and out of grid-like formations). but it’s good to know how that works for future reference.
Hi,
i tried to create a MyComparer but in Unity 2.0 i get following error.
here are the code
...
var openlist = new Array();
openlist.push(new Node2(triangles[hit.triangleIndex * 3 + 0]));
openlist.push(new Node2(triangles[hit.triangleIndex * 3 + 1]));
openlist.push(new Node2(triangles[hit.triangleIndex * 3 + 2]));
openlist.sort(new MyComparer());
...
class MyComparer extends IComparer {
function Compare (a,b) : int {
return a.cost - b.cost;
}
}
...
Thanks for any Help.
Latzi
You need to use Sort with an upper case “S”.