使用 Raycast 时出错

Posted

技术标签:

【中文标题】使用 Raycast 时出错【英文标题】:Error on using Raycast 【发布时间】:2010-12-11 23:19:39 【问题描述】:

我正在尝试使用 Physics.Raycast 方法,但我收到错误消息:

'UnityEngine.Physics.Raycast(UnityEngine.Vector3, UnityEngine.Vector3, float, int)' 的最佳重载方法匹配有一些无效参数。

这很奇怪,因为 itellisense 和文档都告诉我这是允许的:

RaycastHit hit = new RaycastHit();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit)) 
    print(hit.point.ToString());
    selection.transform.Translate(hit.point - selection.transform.position);

有什么想法吗?

【问题讨论】:

【参考方案1】:

我认为你需要在 Physics.Raycast(ray, hit) 中的“hit”之前加上 out 关键字。

RaycastHit hit = new RaycastHit();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) 
    print(hit.point.ToString());
    selection.transform.Translate(hit.point - selection.transform.position);

【讨论】:

【参考方案2】:

在 C# 中,我们必须在变量命中之前使用前驱输出参数 为了获得分配数据给它的函数。

【讨论】:

以上是关于使用 Raycast 时出错的主要内容,如果未能解决你的问题,请参考以下文章