Distance betwen two objects.Error,bug,etc.

I have a problem that I havent been able to solve myself.
I have a simple script that I use in order to find the distance betwen two gameObjects(prefabs) but the script always shows me the distance to a random position in the scene.

#pragma strict

var pos : Transform;


function Start () {

}

function Update () 
{

var distance : Vector3 = pos.position - transform.position;
var posMag : int = distance.magnitude * 10;

print(posMag);
}

It dosent matter what i use as a target … prefab , gameObject ,cube ,sphere.If the script is applied to the prefab it shows me the wrong values BUT if i apply the script to a new gameObject and add a target it shows me the right distance to the applied target prefab.

Is there a problem with the script or with the prefab it is applied to?Any help greatly appreciated.

Make sure that this script goes on the transform you’re comparing with. Other than that make sure posMag is a float value.

Try doing this instead,

#pragma strict
var pos : Transform;

function Update () 
{
    var posMag : float = (pos.position-transform.position).sqrMagnitude;
    Debug.Log(posMag.ToString());
}

Or if you want to use magnitude instead of sqrMagnitude, you could equally do this,

var distance : float = Vector3.Distance(pos.position, transform.position);

Well…every time i apply the script to a prefab it yields the same results the distance goes down right around the center of the scene even with the target applied.But if I apply the script to a new gameObject(not a prefab) it works correctly. It dosent matter what script I use. Is this a bug?

I used the script you provided but I get the same results.

What I want to know is how to get the distance from multiple prefabs with the same script to one and the same target .It dosent give me the right values.