- Home /
Comparing objects in a list to the current gameObject
I want to make a method where I want to compare the distance between this gameObject and each gameObject in a List and get the one that is closest or farthest. I know I can do Vector3.Distance(...) and get a float but I don't know if I should use it in a For or a ForEach loop and how. I feel like it shouldn't be hard but I can't seem to be able to find a way. Anyone got a solution?
Answer by ShadoX · Jun 05, 2021 at 08:56 AM
It sounds like you pretty much know what to do, so it's a bit unclear as to what the problem is. Both For and ForEach work just fine for this. All you need to do is to keep track of the closest and farest objects. Something like:
GameObject closestObject = null;
float shortestDistance = 0;
GameObject farestObject = null;
float longestDistance = 0;
foreach(GameObject obj in list) {
float distance = Vector3.Distance(thisGameObject.transform.position, obj.transform.position);
if(distance > longestDistance) {
farestObject = obj;
longestDistance = distance;
}
if(distance < shortestDistance) {
closestObject = obj;
shortestDistance = distance;
}
}
should work just fine. The only thing I can think of is that you might not want to call this code too often, like in an Update loop for example, especially if you expect to have a lot of objects in that list.
In that case I would suggest to write another method that adds and removes objects to the list and compare those against the closest and farest objects so that you don't have to re-run the for every time the list changes, but rather just against the objects you already have found to be the nearest or furthest away.