- Home /
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.
The pos$$anonymous$$ag variable should be a float value. Why are you multiplying it with 10?
Answer by save · Jan 02, 2013 at 10:12 PM
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);
Answer by Nk.Andrei · Jan 03, 2013 at 07:24 PM
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.
Your answer
Follow this Question
Related Questions
syntax errors 1 Answer
Unity error "scripts exist in multiple locations" 1 Answer
Crash on .exe but fine on editor... 1 Answer
Cant Add Script (or create any new scripts) Javascript 2 Answers
Assertion failed on expression: 0 Answers