There are several things not very efficient here:
- Sorting the whole array is totally unnecessary. You just want the closest.
- You should hold an array with the transform references so you don't need to get each transform everytime.
- Just do a simple min distance search that compares the squared distance. This is much faster than calculating the true distance. The relations stay the same.
Something like that:
Transform nearestMinion = null;
Vector3 myPos = transform.position;
float minDist = 999999;
foreach (Transform Minion in EnemyMinions) // EnemyMinions is now a Transform array or List
float dist = (Minion.position - myPos).sqrMagnitude;
if (dist < minDist)
minDist = dist;
nearestMinion = Minion;
This is the most optimised way. ps, i've written that from scratch, so there might be typing mistakes ;)
This function now returns the nearest Minion or null if there is none at all.
Jul 03 '12 at 05:03 PM