Closest object inside Collider?

To make it easier, I'm going to illustrate them on the same plane
Big purple circle = Object of interest
Bigger pink circle = Trigger collider
Green circle = Object with a Trigger collider and kinematic rigidbody

I would need for the big purple circle to know which one of the green objects is the closest. I am using an OnTriggerStay, but as I noticed it does not return all the objects inside the trigger, and so I can’t use a foreach to iterate through them. How would I need to go about calculating the distance only once, and not for each OnTriggerStay call? And OnTriggerEnter would not work because once I compute the closest target I move to it then that object is destroyed, then repeat the process. Hope this make sense. Thanks for any help

Maybe you can try [Physics.OverlapSphere][1].

Collider[] colliders = Physics.OverlapSphere(center, radius);

Collider nearestCollider = null;
float minSqrDistance = Mathf.Infinity;

for (int i = 0; i < colliders.Length; i++)
	float sqrDistanceToCenter = (center - colliders*.transform.position).sqrMagnitude;*
  • if (sqrDistanceToCenter < minSqrDistance)*
  • {*
  •  minSqrDistance = sqrDistanceToCenter;*

_ nearestCollider = colliders*;_

Hi, how does your script look like ? I am using OnTriggerStay for automatic turret too. It would help me a lot, thanks :slight_smile: