How to sort variables by its value in array

Hey! So i have an array GameObject[ ] and in it, I have got few cars. Ever cars scores points. In my RaceManager i used foreach function to get component which scores points and I when I use Debug.Log function everything is working fine. But I am making positioning system, so I have to sort cars by their score. How to do this? How to sort variables of all cars to point which one should be first, second etc?

public GameObject[] allCars;

void Update () {
        foreach (GameObject car in allCars) {
            carManager = car.GetComponent<NewCarManager> ();
            Debug.Log (car.name + car.score);
}

Try OrderBy or OrderByDescending. For example:

List<GameObject> sortedList = allCars.ToList().OrderBy(x => x.GetComponent<NewCarManager>().score).ToList();
1 Like

it is really bad practice to do things like this per frame like you are doing so in your Update
Likely a better idea to do this in the Start() method and save the result.

using UnityEngine;
using System.Linq;

public class SceneLoader : MonoBehaviour {
    [SerializeField] private GameObject[] allCars;

    private void Start() {
        allCars = allCars.OrderBy(x => x.GetComponent<MyType>().Score).ToArray();
    }
}
2 Likes

Ok! Thanks for the answers! But how do I display sorted value on screen? I mean I know how gui works but how to do it? Thanks in advance!

P.S. Why it should be in Start not in Update?

how do you mean display the sorted value on screen? You mean in the inspector? If yes since its saveing back to the same array the data came from it will display in the inspector sorted.

Reason behind doing this in Start instead of Update, is because the Start Method is run only once, when the game starts or this object is instantiated. while the Update method is run once every from. There is no point calculating the same thing every frame if the data isn’t changing every frame. Expecially since both GetComponent and OrderBy are both expensive operations.

OrderBy doesnt appear to be a real method.
edit: whoops needs using System.Linq; !

1 Like

ToList doesnt appear to be a real method either, maybe im doing something weird
edit: whoops needs using System.Linq; !

they are both extension methods, so you need the System.Linq namespace included. also there is not point in doing .ToList() before the .OrderBy it works on anything that can be enumerated already.

2 Likes