【发布时间】: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