Kyungsik Jeung
Kyungsik Jeung

Reputation: 37

Measuring raycast hitpoint of the specific object

camera is casting a ray to any other object. I am trying to measure hit points(x,y,z) of specific object(screen3D). here is my code

public class EyeTrackingPoint : MonoBehaviour {
public float sphereRadius=250.0f;
public GameObject screen3D;
public Vector3 ScreenPosition;
private void Update()
{
    RaycastHit hit;
    Camera cam = Camera.main;
    Ray ray = new Ray(cam.transform.position, cam.transform.rotation * Vector3.forward * sphereRadius);
    if( Physics.Raycast( ray, out hit) || hit.collider.gameObject.Equals(screen3D)) 
    {
        Debug.Log(hit.point);   
    }
}

}

but, I got null reference exception error. what should I have to do to fix my error. nullReferenceException: Object reference not set to an instance of an object EyeTrackingPoint.Update () (at Assets/EyeTrackingPoint.cs:14)

EyetrackingPoint.cs:14

if( Physics.Raycast( ray, out hit) || hit.collider.gameObject.Equals(screen3D)) 

Thank you for reading.

Upvotes: 0

Views: 284

Answers (1)

Programmer
Programmer

Reputation: 125245

It has something to do with ||. That should be && not ||.

The || means that next condition which is hit.collider.gameObject.Equals(screen3D) will be checked even when Physics.Raycast( ray, out hit) is false.

If Physics.Raycast( ray, out hit) is false and hit.collider.gameObject.Equals(screen3D) is executed, the hit variable will be null and you will get the null exception when you try to use hit.collider.

When you use &&, hit.collider.gameObject.Equals(screen3D) will only be checked if Physics.Raycast( ray, out hit) is true and this is the proper behavior you want.

So you should use this:

if (Physics.Raycast(ray, out hit) && hit.collider.gameObject == screen3D)
{
    Debug.Log(hit.point);
}

OR

if (Physics.Raycast(ray, out hit))
{
    if (hit.collider.gameObject == screen3D)
    {
        Debug.Log(hit.point);
    }
}

Upvotes: 1

Related Questions