Search Unity

Distance to next nearest game object

Discussion in 'Scripting' started by eco_bach, Sep 21, 2017.

  1. eco_bach

    eco_bach

    Joined:
    Jul 8, 2013
    Posts:
    1,601
    Hi
    Give an array or list of game objects, and a particular game object in that array or list, how would I find the distance to the next nearest game object?
     
  2. mysticfall

    mysticfall

    Joined:
    Aug 9, 2016
    Posts:
    649
    I'd suggest something like this:
    Code (CSharp):
    1. // items: IEnumerable<GameObject> - a non-empty collection of game objects to calculate distance from
    2. // position: Vector3 - current position from which to measure distance
    3.  
    4. items
    5.     .OrderBy(i => (i.transform.position - position).magnitude)
    6.     .Reverse()
    7.     .Skip(1)
    8.     .FirstOrDefault();
     
    Ryiah and lordofduct like this.
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,539
    Code (csharp):
    1.  
    2. GameObject[] arr = *the array*;
    3. GameObject targ = *the object your searching against*;
    4. GameObject nearest;
    5. float dist = float.PositiveInfinity;
    6.  
    7. foreach(var go in arr)
    8. {
    9.     if(go == targ) continue;
    10.    
    11.     var d = (targ.transform.position - go.transform.position).magnitude;
    12.     if(d < dist)
    13.     {
    14.         nearest = go;
    15.         dist = d;
    16.     }
    17. }
    18.  
    19. //when reach here, nearest will be nearest.
    20.  
    There are many variations on it. But that's basically it.
     
    Ryiah likes this.