【问题标题】:NullReferenceException when raycasting in unity统一进行光线投射时出现 NullReferenceException
【发布时间】:2021-10-23 04:52:20
【问题描述】:

我正在尝试使用光线投射来写入命中对象的名称和位置,并且在拍摄光线时会给出空引用异常。 它发生在这一行 Ray ray = cam.ScreenPointToRay(Input.mousePosition); 这是代码。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{

Camera cam;

// Start is called before the first frame update
void Start()
{
    cam = Camera.current;
}

// Update is called once per frame
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        //a ray is created
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        //it is then casted
        if (Physics.Raycast(ray, out hit))
        {
            Debug.Log("We have hit " + hit.collider.name + " " + hit.point);
            
        }
    }
}
}

【问题讨论】:

  • 所以可能有些东西是空的。你调试过吗?此外,与其给我们一个行号,让我们计算行数(希望您粘贴正确的代码),不如让它更容易一些,并实际标记哪一行。
  • 你放了相机吗? Camera.current; 可能为空?

标签: c# unity3d raycasting


【解决方案1】:

属性Camera.current

我们当前渲染的相机,仅用于低级渲染控制(只读)。

仅在事件消息OnRenderImageOnPreRenderOnPostRender 中设置/有效

其余时间是null


你宁愿使用Camera.main

第一个启用的相机组件,标记为“MainCamera”(只读)。

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多