title: Find Closest object in Unity 3D
body: <p>I'm trying to write a closest neighbor algorithm, but I'm not sure why it is not working, the cubes are being spawned by an object pool system, and it should take in consideration the other cubes around it that has the same script attached, this is my current script:</p>
  <pre><code>  public class FindNearestNeighbour : Closest, IPooledObject
    {
      public static List&lt;FindNearestNeighbour&gt; findNearestNeighbours = new List&lt;FindNearestNeighbour&gt;();
      private void Start()
      {
          findNearestNeighbours.Add(this);
      }
  
  
      void FindClosestObject(Vector3 from, List&lt;FindNearestNeighbour&gt; transforms)
      {
  
          if (transforms.Count &gt; 1)
          {
              Vector3 location = Vector3.zero;
  
              float Closest = Mathf.Infinity;
              for (int i = 0; i &lt; transforms.Count; i++)
              {
                  Vector3 loc = transforms[i].transform.position;
                  if (from != loc)
                  {
                      float distance = Mathf.Abs(loc.sqrMagnitude - from.sqrMagnitude);
                      if (distance &lt; Closest)
                      {
                          Closest = distance;
                          location = loc;
                          Debug.DrawLine(from, location, Color.red);
                      }
                  }
              }
  
          }
  
      }
  
      public void OnObjectSpawn()
      {
          FindClosestObject(transform.position, findNearestNeighbours);
      }
  }
  </code></pre>
  <p><a href="https://i.stack.imgur.com/gm3lI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gm3lI.png" alt="As you can see, something is not right" /></a></p>