Calculating Distance between two objects in C#

i know you can do Vector3.distance but i want it like this

Distance = Middle
Pivot = Center Of Object

I cant change the pivot to world because i want every other object in local view

Hello there,

If you don’t want the distance between the center of the two objects, you have a few options:

  1. Use Vector3.Distance, but then subtract half the size of each object on the right axis (In your example, I think that would be X). You are left with the distance that your double red arrow indicates in the picture.
  2. Use Vector3.Distance, but from fixed pre-defined points. Basically, add empty children to your objects that will act as “pivots”. Place them at the edge of their parent, and get the distance between them, instead of the parent object themselves.
  3. Use Raycast. Assuming your objects have colliders, you could raycast from one to the other and get the distance that way. Now you want to be careful when you define the starting point of your raycast, as you want it to be the edge of the object, and not the center. For that, you can subtract half the size of the object, or create an empty child “raycast start position” at the edge of the object.

I hope that helps!

Cheers,

~LegendBacon

create two empty gameobjects, place the gameobjects (there pivot) where ever you want and drag your gameobjects into the empty gameobjects.

the distance is the magnitude of the difference between the two pivots

float distance = (go2.transform.position - go1.transform.position).magnitude

but in my case i can’t change pivot like anyhow (Strictly prohibited). Because i have objects with different type of meshes(not only square or rectangular). So i can not subtract “half the size of each object on the right axis” , there are not same size edges.

what i am looking for:-
A method by which i can find all vertices of an object and compare distance from all vertices from another object .

working in Unity 2017.1 (WebGL)
Any reference please?
Thanks in advance…