Distance Between Objects

I’m trying to determine the distance between two objects. The two objects are a blue sphere named “GoodGuy” and a red sphere named “BadGuy”.

I know the formula is … distance = Vector3.Distance(obj1.position, obj2.position) … no problem with that … I’ve been researching it and I found that formula on this site.

Here is what I don’t understand … how do I fill in the syntax on obj1 and obj2 ??? I’m trying all sorts of stuff here and can’t seem to get it. Here’s my code:

private float distance;
private Vector3 obj1;   //  This is location of GoodGuy
private Vector3 obj2;   //  This is location of BadGuy

void Start ()
{
	obj1 = Vector3.zero;   //  What do I put here for vector3 location?
	obj2 = Vector3.zero;   //  And Here?

	distance = Vector3.Distance (obj1, obj2);

	Debug.Log (distance);
}

Vector3.Distance (obj1.position, obj2.position)

Where obj1 and obj2 are Transforms.

Hey so what you have is perfectly fine, and will work perfectly.

The “syntax for obj1 and obj2” will be a Vector3 (a position consisting of an “x,y,z”). It might make more sense if you saw your code like this :

 public Transform obj1;
    public Transform obj2;
    float distanceBetweenThem;
	// Use this for initialization
	void Start () {

	}

    void Update()
    {
        distanceBetweenThem = Vector3.Distance(obj1.position, obj2.position);

        Debug.Log("Distance between obj1 and obj2 is " + distanceBetweenThem);
    }

You are getting the distance between the position of two objects. If you were to look in the inspector, you would see the positions of the objects here:

Position

In your code, when you say “private Vector obj1” - That Vector is made up of obj1’s x,y,z position. You are then checking the distance of that from obj2’s x,y,z position.

So if obj1 was at (0,0,5) and obj2 was at (0,0,7), the distance would be 2.

Hope that helps.

Put the in inspector the two objects in their slots and put in the void Update() to update every frame:

   private float distance;
   public Transform obj1;   //  This is location of GoodGuy
   public Transform obj2;   //  This is location of BadGuy

   void Update()
   {
       distance = Vector3.Distance (obj1.position, obj2.position);
       Debug.Log (distance);
   }

public Transform obj1; // This is location of GoodGuy – Drag and Drop GoodGuy
public Transform obj2; // This is location of BadGuy – Drag and Drop BadGuy
private float distance;

     void Start ()
     {
	    distance = Vector3.Distance (obj1.position , obj2.position);
	    Debug.Log (distance);
     }

I appreciate everyone taking the time to help me understand this. Thanks.