- Home /
Question answered in form of comment by Eric5h5
Sorting array
This should be an easy one, but im having a lil trouble. I have a builtin array of transforms. I have all the names ascending from 1 and up. Im not sure how to sort them by name, tried a custom function of comparing 2 transforms by name and using that in the Sort() function with no luck. I tried a C# version that i was unable to use bcz there was an error and im not to sharp in C#. Im coding unity-java. Can someone help me out, provide some insight and an example. Thanks
Basically, switch to C# (because it's in general a more useful language) and then use generic Lists. They have a 'Sort' function built in.
@syclamoth Can i use generic lists in unity java? Im guessing no, since you said to make the switch to C#.
I was hoping that i could do this using the Array() Sort function. What i have so far doesnt work...
function ChildArray()
{
var array=new Array();
for(var s:int=0;s<transform.childCount;s++)
{
array.push(transform.GetChild(s).transform);
}
array.Sort(Sorter);
}
function Sorter(A:Transform,B:Transform):int
{
return A.name.CompareTo(B.name);
}
Unity doesn't use Java, but you can use Lists in Unityscript/Javascript; there's no reason to switch to C#, it's not in general more useful. People who say that ins$$anonymous$$d of answering the question have...issues. Also there's no reason to use Array, in fact you should stay away from it. If you replace Array with List.<Transform>
in that code (and push with Add), it will work. You can also use Linq, though I'm not a fan of its rather obscure syntax.
array = array.OrderBy(function(a){return a.name;}).ToList();
@Eric5h5 Good deal. I gave it a shot earlier but didnt see there was a period before part of it. Youre right the other method is quite obscure looking.
Thanks for the 2 methods, i ended up writing a brute force method
function SortArray(array:Transform[]):Transform[]
{
var sortedArray:Transform[]=new Transform[array.length];
for(var i:int=0;i<array.length;i++)
{
for(var x:int=0;x<array.length;x++)
{
if(array[i].name==(x+1).ToString())
{
sortedArray[x]=array[i];
break;
}
}
}
return sortedArray;
}
But this is soooo limited and dependent on sequential numbering. Im gonna switch over to the list method, sounds much more efficient and i can save some lines. Thanks!
Follow this Question
Related Questions
Sort Multiple Arrays By Their Length 1 Answer
Matching Index of two Arrays after one Array is sort 3 Answers
Sorting a list by distance to an object? 1 Answer
List.Sort with IComparer 2 Answers