Hey, all,
I know this may sound like a dumb question, but is there any easy way to find the closest object to a point in Unity?
Problem being that, in order to test for distances, you need to use Vector3.Distance, but doing so gives the distance from a fixed point to the pivot point of the second object - what I want is which object is the closest to me at it’s extents.
The only solution I can come up with is to use colliders and the CheckSphere function, but I expect that’s pretty expensive from a performance standpoint?
Any ideas?
Cheers,
SB.
You have access via script to a mesh or collider’s bounding box, including it’s extents to subtract from your calculated distance.
As for performance, you won’t want to use Vector3.Distance is that’s your desire. It uses a square root under the covers. Use sqrMagnitude instead when comparing vector lengths.
So how do I relate sqrMagnitude to the distance between two points? I need to square the distance I’m comparing the computed distance to?
So:
if ( Vector3.Distance (point1, point2) > 20.0f )
becomes
if ( (point2-point1).sqrMagnitude > (20.0f*20.0f) )
?
Cheers,
SB
Yes, that’s how you do it. Just a word of caution… you should always multiply the value by itself rather than use the Mathf.Pow function to square the value (even if it is a long variable or constant name that takes ages to type 
Also look at Physics.OverlapSphere(), which will give you a set of colliders inside of a distance sphere, at the very least it would shrink the number of objects you need to test against