finding nearest object in array not working

So I basically have enemies. I want them to be heading toward my “goal” object, unless a “defender” object is within a certain range of them, in which case they will head towards that instead.

Here is the method for finding the closest defender:

private Transform findClosestDefender(float range)
    {
        Transform currentDefender;
        if(defenders.Count > 0)
        {
            for(int i = 0; i < defenders.Count; i++)
            {
                RaycastHit hit;
                if(Physics.Raycast(transform.position, defenders[i].transform.position, out hit, range))
                {
                    Debug.DrawRay(transform.position, defenders[i].transform.position);
                    if(hit.distance < nearestDistance)
                    {
                        nearestDistance = hit.distance;
                        currentDefender = defenders[i].transform;
                    }
                }
            }
        }
        return null;
       
    }

However, when this is run, two things go wrong.

  1. the Debug.DrawRay doesn’t show up (making me think there is something wrong with how I’m doing the ray)
  2. findClosestDefender(10) returns null, even if a defender object is right next to the enemy.

Any ideas?

Why are you using raycasts? If you just want the distance use

Vector3.Distance (transform.position, defenders[i].transform.position)

Indeed, if you only want the distance, you can use Vector3.Distance(a, b), (or some people prefer (a-b).SqrMagnitude() and compare it to range*range to avoid calculating a square root.)

But I would say the real problem lies with what you return from your function. It’s always going to be null. Instead, return currentDefender. Also pay attention to what your nearestDistance is going to be, I assume it’s a property of the class? Does it need to be? If not, maybe better to bring it inside the method…

public Transform FindClosestDefender()
{
  Transform nearestDefender = null;
  // we'll use a huge number so it should always pass the first time.
  float nearestDistance = 10000f;
  foreach (var defender in defenders)
  {
    var distance = Vector3.Distance(transform.position, defender.position);
    if (distance < nearestDistance)
    {
      nearestDistance = distance;
      nearestDefender = defender;
    }
  }

return nearestDefender;
}

Oh, and if you’re not seeing your ray, maybe try supplying it with a color that makes it noticable.