unity 3d student

Beginner B21 – Finding Distance with Vector3

Finding the distance between two points in 3D space using Vector3.Distance command

Code Used (Javascript)

  1. var box : Transform;
  3. function Update () {
  5.  var dist : float = Vector3.Distance(box.position, transform.position);
  6.  Debug.Log(dist);
  8.  if(dist <= 10){
  9.   light.enabled = true;
  10.  }else{
  11.   light.enabled = false;
  12.  }
  13. }

Further Reading

Share via Social Media

  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • Add to favorites


    While Distance( … ) is good, it is mathematically expensive- The alternative approach is taking the squared magnitude, or the summed magnitude of it’s components, then forgoing the final root for distance, which cuts out the most expensive mathematical element of it, but gives you a return that is valid in terms of comparison. To do this in the above example, you would use (box.postion – transform.position).sqrMagnitude

    Another optimization would be to cache the objects Transform, by setting a private variable during Awake (Because transform always does a GetComponent(Transform), which takes allot longer then if you know what transform your using)

    • Can you make a video explaining please?

    Quick question, does the DistCheck script that you dragged on to the point light contain the same coding as the lightSwitch script you work on during the video?

    • ERROR SPOTTED! WELL DONE! Hey everyone thanks to eagle eyed Charlotte (not to be confused with Cherry) who spotted my mistake of dragging the wrong – albeit identically coded DistCheck instead of the lightSwitch script written in the video. The ‘DistCheck’ script is the same – just one i’d written in a practice before recording the video and forgotten to delete – my bad sorry! If I have time I’ll re-record this..

    Quality work, I am impressed of the detail and Work that you, and yours:) have put on this project and Wish You the Best,

  • Sorry: these comments allow HTML, didn’t realise.

    < is shown as & l t ; without all the spaces.

    Delete my other one.

  • This only works with Directional light though… Why is that?

Leave a Comment