英文:
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<PickUp>();
// Perform actions with the target object
} else {
// No object was hit by the raycast
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论