- Home /
Sorting a list by distance to an object?
Hi. I think similar questions have been answered already, but I have had a hard time understanding those answers.
Basically, I want to sort a list of transforms by distance to the player, so the closest transform is at the top and of the list and farthest is at the bottom. I don't use lists that often so I'm not too familiar with their sort functions or how they work. A sample script or explanation would be greatly appreciated.
Thanks.
Answer by Paricus · Dec 17, 2016 at 04:51 PM
This ended up working for me, never used linq or OrderBy before so I'm still not too sure why this works but it does. If someone has a better method or can explain this method, I'd be happy to hear it.
using UnityEngine;
using System.Collections;
using System.Linq;
public class SortDistance : MonoBehaviour {
public GameObject[] points;
public GameObject sphere;
void Start()
{
points = points.OrderBy(point => Vector3.Distance(sphere.transform.position, point.transform.position)).ToArray();
foreach (GameObject point in points)
Debug.Log(point.name);
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SortDistance : MonoBehaviour
{
public GameObject sphere;
public List<Transform> spawnPoints;
void Start()
{
Sort();
}
void Sort()
{
spawnPoints.Sort(delegate (Transform a, Transform b)
{
return Vector3.Distance(sphere.transform.position, a.transform.position).CompareTo(Vector3.Distance(sphere.transform.position, b.transform.position));
});
foreach (Transform point in spawnPoints)
Debug.Log(point.name);
}
}
This method also seems to work. Taken from http://answers.unity3d.com/questions/246781/sort-transforms-by-distance-to-player.html If anyone has the same problem.
Your answer
Follow this Question
Related Questions
Show Top 10 Of 1 GameType 2 Answers
How to arrange list 3 Answers
Sorting Variables Help 1 Answer
Matching Index of two Arrays after one Array is sort 3 Answers