How would i make this code not lag the game

void GetNearestMinion()
{
foreach (GameObject Minion in EnemyMinions)
{
float finishTime = Time.time + waitTime;
MinionsTransforms.Add(Minion.transform);

        }
        MinionsTransforms.Sort(delegate(Transform t1, Transform t2) { return (Vector3.Distance(t1.position, t2.position).CompareTo(Vector3.Distance(t2.position, transform.position))); });
        
        nearestMinion = MinionsTransforms[0].gameObject;
    }

How can i stop this from lagging the game keep in mind that every minion does this check at least once every frame(which i don’t mind reducing)?

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 GetNearestMinion()
{
    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;
        }
    }
    return nearestMinion;
}

This is the most optimised way. ps, i’ve written that from scratch, so there might be typing mistakes :wink:

This function now returns the nearest Minion or null if there is none at all.