在Unity中使用未分配的局部变量

时间:2015-07-07 13:44:46

标签: c# unity3d

这是我控制镜头移动的脚本.. 但是我得到了错误:

  

错误CS0165:使用未分配的局部变量`floorHit'

我该如何解决?

void Start(){
    floor = LayerMask.GetMask ("Floor");
    Ray RAY = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit floorHit;
    Vector3 playerMouse = floorHit.point - transform.position;
    playerMouse.y = 0f;
    MoveTo (playerMouse.x, playerMouse.z);
}

3 个答案:

答案 0 :(得分:6)

需要通过添加线

来设置光线的值
if (Physics.Raycast (ray, out floorHit)) {
    //add logic here for what to do if we hit
    }

宣布之后。

所以完整的例子是

void Start(){
    floor = LayerMask.GetMask ("Floor");
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit floorHit;
    if (Physics.Raycast (ray, out floorHit)) {
        Vector3 playerMouse = floorHit.point - transform.position;
        playerMouse.y = 0f;
        MoveTo (playerMouse.x, playerMouse.z);
    }
}

答案 1 :(得分:2)

您需要RaycastHit - 类的新实例:

RaycastHit floorHit = new RaycastHit();
Vector3 playerMouse = floorHit.point - transform.position;

答案 2 :(得分:1)

您需要实例化floorhit

RaycastHit floorHit = new RaycastHit();