- Home /
Sort array by ascending numerical order
How do I sort an array by ascending numerical order? I'm trying to create a high score script, and found sort() in w3schools. A Sort() is also in the Unity scripting reference, so I was wondering if it can still work with numbers rather than text.
Here is my code:
private var HighScores : Array;
function sortScore(a, b){
return a - b;
}
function CheckHighScores(NewTime : Score){
HighScores.Push(NewTime);
HighScores.Sort(sortScore);
if (HighScores.length>10){
HighScores.Pop();
}
}
Thanks.
It gives me this error: $$anonymous$$issing$$anonymous$$ethodException: $$anonymous$$ethod not found: 'Score.op_Subtraction'.
Answer by Peter G · Jul 20, 2011 at 07:05 PM
The Unity Scripting reference doesn't say there is an overloaded version of Array.Sort that takes a function type as a parameter. Now, maybe its undocumented, but that probably means you can't input a custom sorting method into Unity's sort class. You could change to generic List easily though and that does allow for a custom comparison.
import System.Collections.Generic;
private var HighScores = new List.<int>();
function sortScore(a, b){
return a - b;
}
function CheckHighScores(NewTime : Score){
HighScores.Add(NewTime);
HighScores.Sort(sortScore);
}
Thanks, that got rid of a lot of errors. But it now gives me this: The best overload for the method 'System.Collections.Generic.List.Add(int)' is not compatible with the argument list '(Score)'.
Sorry I completely overlooked that. Your time should be an int
not a score so it should look like:
function CheckHighScores (NewTime : int) {
You can change the underlying type to score if you want to, but then you have to have a Score
class and you need to modify the sort method slightly.
How can I "check" your comment ins$$anonymous$$d of the answer?