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();
}
}
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);
}