Find closest collider still returning all colliders?

public class PlayerInteractor : MonoBehaviour
{
public Collider rangeSphere;

 void OnTriggerStay (Collider inRange) {
 float closestDist = Mathf.Infinity;
 Collider closestTarget = null;
 Collider[] allTargets = inRange.GetComponentsInChildren<Collider>();
 
 foreach (Collider target in allTargets) {
     float distToTarget = Vector3.Distance(target.bounds.center, rangeSphere.bounds.center);
     if (distToTarget < closestDist) {
         closestDist = distToTarget;
         closestTarget = target; }
 }
 Debug.DrawLine(closestTarget.bounds.center, rangeSphere.bounds.center, Color.red); }
 }

Your code might be a little too cut up to understand your problem. Can you post the relevant method?

However, your problem might stem from this line:

  float distToTarget = Vector3.Distance(inRange.bounds.center, rangeSphere.bounds.center);

It makes no reference to your list of collider targets using “target”.

Why does your method return an array of colliders and not a single collider, if it’s supposed to return the closest one?

Not sure why, but it was missing a conditional “if” at the OnTriggerStay start. Seems to be working now :slight_smile:

void OnTriggerStay (Collider inRange) {
    if (inRange.tag != "Player") {
        float minDist = Mathf.Infinity;
        Interactable tMin = null;
        Interactable[] allTargets = GameObject.FindObjectsOfType<Interactable>();
    
        foreach (Interactable target in allTargets) {
        float dist = (target.transform.position - range.bounds.center).sqrMagnitude;
        if (dist < minDist) {
            minDist = dist;
            tMin = target; } }