I keep getting the error "Use of unassigned variable" for "hit" for my raycast but I assign it. Here it is in the code

huangapple go评论56阅读模式
英文:

I keep getting the error "Use of unassigned variable" for "hit" for my raycast but I assign it. Here it is in the code

问题

我弄不清楚为什么代码在那里出问题。
英文:
Vector3 screenPoint = new Vector3(cam.pixelWidth / 2, cam.pixelHeight / 2, 0);
        Ray ray = cam.ScreenPointToRay(screenPoint);
        RaycastHit hit;
        GameObject hitObject = hit.transform.gameObject;
        PickUp target = hitObject.GetComponent<PickUp>();

i cant figure out why the code is breaking right there.

答案1

得分: 1

这是因为您在分配值给它之前尝试访问 hit 变量:

Vector3 screenPoint = new Vector3(cam.pixelWidth / 2, cam.pixelHeight / 2, 0);
Ray ray = cam.ScreenPointToRay(screenPoint);
RaycastHit hit;

if (Physics.Raycast(ray, out hit)) {
    GameObject hitObject = hit.transform.gameObject;
    PickUp target = hitObject.GetComponent<PickUp>();
    // 使用目标对象执行操作
} else {
    // 射线未击中任何对象
}
英文:

That's because you try to access the hit variable before assigning a value to it:

Vector3 screenPoint = new Vector3(cam.pixelWidth / 2, cam.pixelHeight / 2, 0);
Ray ray = cam.ScreenPointToRay(screenPoint);
RaycastHit hit;

if (Physics.Raycast(ray, out hit)) {
    GameObject hitObject = hit.transform.gameObject;
    PickUp target = hitObject.GetComponent&lt;PickUp&gt;();
    // Perform actions with the target object
} else {
    // No object was hit by the raycast
}

huangapple
  • 本文由 发表于 2023年6月6日 04:03:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409652.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定