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评论87阅读模式
英文:

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

问题

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

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

答案1

得分: 1

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

  1. Vector3 screenPoint = new Vector3(cam.pixelWidth / 2, cam.pixelHeight / 2, 0);
  2. Ray ray = cam.ScreenPointToRay(screenPoint);
  3. RaycastHit hit;
  4. if (Physics.Raycast(ray, out hit)) {
  5. GameObject hitObject = hit.transform.gameObject;
  6. PickUp target = hitObject.GetComponent<PickUp>();
  7. // 使用目标对象执行操作
  8. } else {
  9. // 射线未击中任何对象
  10. }
英文:

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

  1. Vector3 screenPoint = new Vector3(cam.pixelWidth / 2, cam.pixelHeight / 2, 0);
  2. Ray ray = cam.ScreenPointToRay(screenPoint);
  3. RaycastHit hit;
  4. if (Physics.Raycast(ray, out hit)) {
  5. GameObject hitObject = hit.transform.gameObject;
  6. PickUp target = hitObject.GetComponent&lt;PickUp&gt;();
  7. // Perform actions with the target object
  8. } else {
  9. // No object was hit by the raycast
  10. }

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:

确定