One of the objects is always a rotated straight line (a square, really). The other is not constant, but is a character shape. The ColliderDistance2D would work, if it were for 3D. (However, after a test I can verify that the distance is slightly wrong anyway). A raycast or a rb.SweepTest is too expensive, specially since the distance between both shapes can be very large, and also because the whole point of all of this is a broad phase for collision detection.
I found this buried in Unity answers and used it ever since.
GameObject nearest;
void Start()
{
var distance = Mathf.Infinity;
var position = transform.position;
var objects = GameObject.FindGameObjectsWithTag("Tag");
foreach(GameObject thisObject in objects)
{
var diff = (thisObject.transform.position - position);
var curDistance = diff.sqrMagnitude;
if(curDistance < distance)
{
nearest = thisObject.gameObject;
distance = curDistance;
}
}
}
It basically starts distance
from infinity and checks if the distance of the next object in the array is nearer than distance
, if so distance
is set to that objects distance and in turn finds the nearest.