- Home /
Get distance between 2 gameObjects?
Hi, I know how to print out the position of an object to the console. I am actually pretty good with coding, just not in Unity yet. I am used to doing small applications in Visual Studio. I simply need to know how to get the distance from one object to the other. I'd imagine I can use an if statement to make something happen if the distance is a certain range that I declare?
Answer by ZenithCode · Aug 12, 2013 at 09:07 PM
You can do something like this:
 public GameObject go1;
 public GameObject go2;
 
 void Awake()
 {
    if (go1 != null && go2 != null)
    {
       Vector3 dist = Vector.distance(go1.transform.position, go2.transform.position);
       Debug.Log(string.Format("Distance between {0} and {1} is: {2}", go1, go2, dist));
    }
 }
Reference: http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Distance.html
This is the easiest way to get distance between two gameObjects. I just wanted to add two things to this answer.
- If you want to constantly check the distance (as in you want something to happen when A is close to B), make sure to throw the function Vector.distance() into the update function. Be sure to declare the Vector3 outside of update though. 
- If the script is attached to one of the GameObjects you are actually trying to check, you only need one public GameObject variable. ins$$anonymous$$d of go2.transform.position, you can just use this.gameObject.transform.position. 
Not sure if Dismortus knew these differences or not, so I just thought I'd make mention of them.
Yes I gave an overview but on how to get the distance. I totally agree with deadfish90's recommendations (if they fit your purpose)
Thank you very much, this was easier than I thought it would be :)
Answer by Triqy · Aug 12, 2013 at 09:26 PM
You can use transform.LookAt(Target) to look at the gameobject you want to find the distance between then you could shoot a raycast at the gameobject using Vector3.Distance to find the distance
I'm sorry, I may have misread, but to "shoot a raycast at the gameObject using Vector3.Distance" doesn't seem to make sense to me. Perhaps you could reword? I am new to Unity's classes.
A raycast is sending a "beam" in a direction. That beam can "collide" with other objects. Once that beam (raycast, or cast a ray) hits, you can get the distance using Vector3.Distance.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                