Need help sorting an array!

Hey everybody, so I have an array of racers for my racing game. I’m trying to set up a checkpoint system that can give me the position of every player(first, second, third…) based on its distance from the checkpoint. So I have a for statement that gets every racer in the array and gets its distance from the checkpoint, but how would I go about sorting them? Is there anyone out there that thinks they can help me out?

Heres the code so far in case it helps.

function UpdateRanks () {
    for(var racer:GameObject in AIRacers){
        var dist = GetDistance(racer);
    }
}

With Linq?

list.Sort((playerA, playerB) => playerA.Distance.CompareTo(playerB.Distance));

or something like that…

Hey, thanks for the quick answer LightStriker, I really appreciate it. But I need to compare everyone in the array, not just player a and b. I need to compare player a to everyone then player b to everyone and so on and so on. Any ideas on how to do this, or is there some tutorial I could watch or read that would explain this subject more in depth? Not on arrays in general but more specifically, on how to sort them in unity?

Also my code is in java, in case it makes a difference.

It’s a lambda expression, PlayerA and PlayerB are automatically assigned variable for every comparison loop. Try it.

Huh… Well, I have no idea if you have access to Linq in JS.

Sounds like you want an insertion sort.

Nevermind, I figured it out. I was going about it all wrong. I’ll explain in case anyone else is ever trying to do something similar.

The key wasn’t to make an array that was ordered according to the position of the competitor. What I needed to do was Give each individual racer its own place int, then make a function something like this.

function GetPlace(){
var racerAR = RaceController.AIRacers;
Place = 1;
for(var racer:GameObject in racerAR){
    if(racer.GetComponent(NavigationController).PlaceDistance < PlaceDistance){
        Place++;
        }
    }
}

Every time its called it sets the place int to one. Then for every racer in the racer array, it compares the place distance value ( I couldn’t think of anything better to name it) to that racers place distance value. If the place distance of a racer is lower than this racers place distance, than this racer knows that the other racer is ahead of them and the place int gets incremented. Once you have done this for every racer in the array, then you have your place.

When it comes to getting the place distance values, right now I’m using something like

PlaceDistance = DistanceFromCheckpoint - (CurrentCheckpointIndex5000) - (CurrentLap50000)

I know its not perfect, but I just figured it out, so I’m still working on it. But this should at least point you on the right track if your having similar problems. And thanks for all your help anyway guys:)