distance between object and raycast hit.point

Im new to Raycasting and have manageed to write some code that allows the casting to emit and tell me what gameObject it’s pointing at which is great.

I know want to be able to specify at what distance it tells me what game object im pointing at so…enter RaycastHit.distance.

I looked on the Unity website script reference and there is barely any information on it and how to use it. I have tried to incorporate it in script in a number of ways to get the distance between the camera that is emitting the ray and the rays hit point but with no luck.

Does anyone know how I would use this to get the distance between my camera and any varying hit point?

here are some of the attempts that I have played around with but haven’t succeeded with

activation_distance = (RaycastHit.point - Camera.main.transform.position)

activation_distance = Vector3.Distance(Camera.main.transform.position, RaycastHit.point);

RaycastHit.distance = Camera.main.transform.position, hit.point;

RaycastHit.distance(Camera.main.transform.position, hit.point);

You’re confusing two different things. In Physics.Raycast, you can use the optional parameter distance to specify the ray detection range. If you don’t use it, the ray will go from the starting point to infinite. Usually you only use this parameter if you want to limit the Raycast detection range - if you want to check if something is at up to 10m, for instance.

Upon return, if Raycast returns true, the RaycastHit hitInfo structure is filled with hit data, what includes distance - the distance from the ray starting point to the hit point, in this case.

Take a look at the last example in Physics.Raycast. You can also see two different usages in the following:

// create a ray starting at the camera and passing through the mouse pointer
var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit: RaycastHit;
// do a infinite Raycast from the camera
if (Physics.Raycast(ray, hit)) print("Hit something at "+hit.distance+" meters");
// do a Raycast up to 50 meters from the starting point
if (Physics.Raycast(ray, hit, 50)) print("Hit "+hit.transform.name);