What is the most effective way to get the closest target

What is the most effective and less expensive way to get the closest target from these two methods?

Using LINQ

GameObject FindClosestTarget(string trgt) 
{
    GameObject[] closestGameObject = GameObject.FindGameObjectsWithTag(trgt)
                      .OrderBy(go => Vector3.Distance(go.transform.position, transform.position)
                      .FirstOrDefault();
         return closestGameObject ;
}

or

 GameObject FindClosestTarget(string trgt) 
     {
         GameObject[] gos= GameObject.FindGameObjectsWithTag(trgt);

         GameObject closest=null;
         float distance = Mathf.Infinity;
         Vector3 position = transform.position;
         foreach (GameObject go in gos) {
             Vector3 diff = go.transform.position - position;
             float curDistance = diff.sqrMagnitude;

             if (curDistance < distance) {
                 closest = go;
                 distance = curDistance;
             }
         }

         return closest;
     }
+4
source share
3 answers

The first example uses Vector3.Distanceone that requires a rather expensive operation Sqrt, and the second uses code that I would prefer to use in favor of a simpler LINQ form.

Here is an excerpt from the API documentation for Unity Scripting for sqrMagnitude:

v Mathf.Sqrt(Vector3.Dot(v, v)). Sqrt , . - Sqrt. , , .

, , sqrMagnitude... Sqrt - , , , .

:

GameObject FindClosestTarget(string trgt)
{
    Vector3 position = transform.position;
    return GameObject.FinndGameObjectsWithTag(trgt)
        .OrderBy(o => (o.transform.position - position).sqrMagnitude)
        .FirstOrDefault();
}

... ( ) LINQ Sqrt, .

, , , , , . # .

, , sqrMaginitude, Sqrt.

+8

EDIT: , , sqrt, .

, , , , , , ( O (n * log (n ))), , (O (n)).

, , ... .

+3

gameObject , . . , gameObject.

, , . , , . (, , )

+1

Source: https://habr.com/ru/post/1611749/


All Articles