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*.transform.position, out hit, range))*

{
Debug.DrawRay(transform.position, defenders*.transform.position);*
if(hit.distance < nearestDistance)
{
nearestDistance = hit.distance;
currentDefender = defenders*.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?

Well, that function is ALWAYS going to return null, since that is what you return on line 20.

Perhaps you want to add this after line 15:

return currentDefender

As @jmonasterio said, that function will always return null, however their suggestion won’t give the result you want. That’ll return the first defender that’s less than nearestDistance, even if there are others in the array that are closer.

You should replace line 20 with return currentDefender. That will return the closest found, or null if it goes through the loop without finding one. Also, the if(defenders.Count > 0) is redundant; if defenders.Count is zero, the for() loop won’t run anyway.

Next, you’re not setting nearestDistance in the method, so if not set elsewhere, it will never find a defender as it’ll start at 0. Unless you want it to carry over from previous runs of the method, perhaps set it to ‘range’ at the start?

Finally, a few things with the DrawRay. First is by default it only lasts for one frame, so you may simply not be seeing them. You can give an optional duration as the fourth parameter (third is optional color). Second issue is it draws in Scene view, are you looking there for the rays? Finally, you’re sending a position as the second parameter, but unlike raycast, DrawRay can only be sent origin and direction, not start and end points. You can use DrawLine to use start and end points.