【问题标题】:Measuring raycast hitpoint of the specific object测量特定对象的光线投射生命值
【发布时间】:2021-09-13 20:29:12
【问题描述】:

相机正在向任何其他对象投射光线。 我正在尝试测量特定对象(screen3D)的命中点(x,y,z)。 这是我的代码

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);   
    }
}

}

但是,我得到了空引用异常错误。我应该怎么做才能解决我的错误。 nullReferenceException:对象引用未设置为对象的实例 EyeTrackingPoint.Update () (在 Assets/EyeTrackingPoint.cs:14)

EyetrackingPoint.cs:14

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

感谢您的阅读。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    它与|| 有关。那应该是&& 而不是||

    || 表示即使Physics.Raycast( ray, out hit)false,也会检查下一个条件hit.collider.gameObject.Equals(screen3D)

    如果Physics.Raycast( ray, out hit)false 并执行hit.collider.gameObject.Equals(screen3D),则hit 变量将为空,当您尝试使用hit.collider 时,您将得到空异常。

    当您使用&& 时,只有当Physics.Raycast( ray, out hit)true 并且这是您想要的正确行为时,才会检查hit.collider.gameObject.Equals(screen3D)

    所以你应该使用这个:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多