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