# How can I get the distance between two objects?

Hello. How can I get the distance between two (moving) objects and then have a function dependent on the distance (ex: if distance > 10...)? Thanks

``````var obj1 : Transform;
var obj2 : Transform;

function Update() {
var distance = Vector3.Distance(obj1.position, obj2.position);
if (distance > 10.0f) {
}
}

``````

Though, in terms of performance, you might be better off using the square of your distance (fewer square roots to calculate) and do something like:

``````var sqrDistance = (obj1.position - obj2.position).sqrMagnitude;

// Note you also need to calculate the square of the test,
// so 100.0f = 10.0f * 10.0f
if (sqrDistance > 100.0f) {
}

``````

`Vector3.Distance(transform.position, othertransform.position);` will return the distance between the position of this object and the position of the object that we have assigned othertransform to. We could use this in code (javascript) like such:

``````var othertransform : Transform;

function Awake()
{
othertransform = GameObject.FindWithTag("Target").transform;
}

function Update()
{
if (Vector3.Distance(transform.position, othertransform.position) > 10)
{
DoSomething();
}
}

``````

Update is called each frame, so it will always have an accurate distance reading.

just put a distance function in the function Update, and also do a if(distance > 10) in the function Update.

so something like

``````var that : Transform;
function Update()
{
var distFromPlayer = Vector3.Distance(that.position, transform.position)
if(distFromPlayer > 10)
{
//do more stuff here.
}
}

``````

i think might work.