Raycast 没有击中我点击的内容

Raycast is not hitting what I click

这是 3D 的。当我点击 Player 对象时,我的 Raycast 没有击中它。光线投射调试线满屏乱飞,而且只画了一次。重新点击不会重绘。我故意补偿并点击空 space 以点击并让光线穿过我的 Player 对象。即便如此,它也不算命中。该脚本附加到一个空对象,该对象没有相关标签。

我在这里已经看过类似的答案,看起来是正确的。请告知我做错了什么。添加了几个屏幕截图。谢谢。

这是抛出的错误:

NullReferenceException: Object reference not set to an instance of an object Player.isPlayerClicked () (at Assets/Player.cs:24) Player.Update () (at Assets/Player.cs:18)

public class Player : MonoBehaviour{

    private Ray ray;
    private RaycastHit hit;

    private void Start(){
        if (Camera.main != null) ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        else{
            Debug.Log("Camera is null"); // this doen't print meaning cam is valid
        }
    }

    private void Update (){
        isPlayerClicked();
    }

    private bool isPlayerClicked(){
        if (Input.GetMouseButton(0)){
            Debug.DrawRay(ray.origin, ray.direction * 100, Color.green, 100f); // only draws once. Re-clicking does nothing
            Debug.Log("mouse clicked " + hit.transform.name); // this is throwing error. hit seems to be invalid. 
            if (!Physics.Raycast(ray, out hit)) return false;
            if (!hit.transform.CompareTag("Player")) return false;
            Debug.Log ("Player clicked");
            return true;
        }
        return false;
    }
}

唯一应该使用 Physics.Raycast 函数返回的 RaycastHit 变量的时间是 Physics.Raycast returns true。如果 Physics.Raycast returns false,请不要费心使用或检查 RaycastHit 值,因为它始终是 null。同样,如果 Physics.Raycast returns falsehit.transform 将是 null,因此您必须仅在光线投射实际命中某些东西时才使用结果。

您的函数可以简化为以下内容(注意结果在 if 语句中的使用方式,并且仅当它 returns true):

private bool isPlayerClicked()
{
    if (Input.GetMouseButton(0))
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Debug.DrawRay(ray.origin, ray.direction * 100, Color.green, 100f); // only draws once. Re-clicking does nothing
        Debug.Log("mouse clicked"); 
        if (Physics.Raycast(ray, out hit) && hit.transform.CompareTag("Player"))
        {
            Debug.Log("Player clicked " + hit.transform.name);
            return true;
        }
    }
    return false;
}

由于您只想检测 3D 游戏对象上的时钟,因此请使用 EventSystem。具有 IPointerClickHandler 接口的 OnPointerClick 函数应该可以解决这个问题。请参阅 post 中的 #6 了解如何进行设置。这将适用于移动和桌面平台。