使用Raycasts2D Unity C#获取错误

时间:2017-02-09 16:39:21

标签: c# unity3d

我正在开发一个使用光线投射作为射击机制的一部分的项目。出于某种原因,虽然我在使用光线投射时遇到错误,但我不确定如何修复它们。这是我的代码:

void Shoot(){
    RaycastHit2D hit;

    if (Physics2D.Raycast(player.position, player.forward, out hit, weapon.range, targetMask)) {
        Debug.Log ("You Hit: " + hit.collider.name);
    }
}

我得到的错误是:

Assets / Scripts / Shooting.cs(26,17):错误CS1502:“UnityEngine.Physics2D.Raycast(UnityEngine.Vector2,UnityEngine.Vector2,float,int,float)”的最佳重载方法匹配有一些无效参数

Assets / Scripts / Shooting.cs(26,62):错误CS1615:参数'#3'不需要'out'修饰符。考虑删除“out”修饰符

感谢您提出任何建议,为什么会这样......

1 个答案:

答案 0 :(得分:3)

Unity documentation for 2D Raycasts可能不清楚您可以使用什么。以下是所有可用的方法:

Raycast(Vector2 origin, Vector2 direction) : RaycastHit2D

Raycast(Vector2 origin, Vector2 direction, float distance) : RaycastHit2D

Raycast(Vector2 origin, Vector2 direction, float distance, int layerMask) : RaycastHit2D

Raycast(Vector2 origin, Vector2 direction, float distance, int layerMask, float minDepth) : RaycastHit2D

Raycast(Vector2 origin, Vector2 direction, float distance, int layerMask, float minDepth, float maxDepth) : RaycastHit2D

与3D光线投射不同,没有可用的重载使用out修饰符。

(简而言之,你使用的是一种不存在的方法,它特别抱怨out hit

他们都返回RaycastHit2D 结构。这意味着您无法将其与null进行比较以查看命中是否有效。所以,根据变量的名称,我认为你的意思是:

void Shoot(){
    RaycastHit2D hit;

    hit = Physics2D.Raycast(player.position, player.forward, weapon.range, targetMask);

    // As suggested by the documentation, 
    // test collider (because hit is a struct and can't ever be null):
    if(hit.collider != null){
        Debug.Log ("You Hit: " + hit.collider.name);
    }
}