Linq not working
I am trying to reorder a list based on how far each game object is away from the player. When I call it, nothing happens to the list and no errors are given.
I didn't forget
using System.Linq;
These are my variables:
public GameObject player;
public List<GameObject> persons = new List<GameObject>();
Here is my function:
private void Reorder(Vector3 p)
{
persons = persons.OrderBy(x => Vector2.Distance(p,x.transform.position)).ToList();
}
And I call it like this in the update function when I press a key
Reorder(player.transform.position);
Why is it not working?
Do the variables and the method belong to the same class?
Answer by jg_unity917 · Dec 19, 2019 at 04:16 PM
I don't know if it'll fix your issue but, use the Sort() method.
persons.Sort( (first, second) =>
{
float distance1 = (first.transform.position - p).sqrMagnitude;
float distance2 = (second.transform.position - p).sqrMagnitude;
return distance1.CompareTo(distance2);
});
It's better performance-wise and modifies the List in place. If you only need to know if one is further away than the other, use sqrMagnitude instead.
Yeah, it didn't work... For some reason, using this.transform.position works, but on the wrong game object. I'll just put a script on the player that reorders the list. Thanks for your help
Your answer
Follow this Question
Related Questions
New Vector2 won't take effect when called from another script in the same GameObject. 0 Answers
Using a specific function from a generic object. 0 Answers
Need help to generate a random assortment of 4 buttons - C# 0 Answers
Passing enemy statistic to FightController 0 Answers
Changing a Prefab's Text component seems to be broken. 1 Answer