How to find a gameobject with the most of a float?
I need to find out which gameobject has the most threat generation in my game but I can't figue it out. The only code I have trying to do this is:
public GameObject [] onlinePlayers;
public GameObject player;
void Update () {
// Find All Online Players
onlinePlayers = GameObject.FindGameObjectsWithTag ("PlayerHolder");
player = Mathf.Max (//I don't know what to put here);
}
Answer by Dinosaurs · Oct 22, 2015 at 08:43 PM
The easiest way would probably be using LINQ:
using System.Linq;
[...]
player = onlinePlayers.OrderByDescending(item => player.Threat).FirstOrDefault();
This isn't the best solution though, as Linq uses quite a bit of memory; a more performant way of handling this might be to have another class maintain the list of players, sorted by how much threat they have, and sort the list when a player does something that generates threat. This would also mean you wouldn't need to search for all players by tag every Update().
It's worth noting that First() throws an exception if there is no result, a safer option is FirstOrDefault() and then null check the return.
Ah yeah, good call, I'll edit that into my answer.