我正在统一使用 Raycast,我想在单击它时获取对象的位置,但我不工作,我不知道我做错了什么
I am using Raycast in unity and i want to get the position of an object when i click on it but i does not work and i don't know what i am doing wrong
所以当我点击游戏中的对象时,我得到了这个错误...
NullReferenceExceptionm:未将对象引用设置为对象的实例
JumpDestination.Update () (在 Assets/Scripts/JumpDestination.cs.:12)
我不知道我做错了什么,我该如何解决?
我想获取被击中物体的位置
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JumpDestination : MonoBehaviour {
private RaycastHit hit;
public float jumpMaxDistance;
void Update(){
Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit, jumpMaxDistance);
if (hit.collider.gameObject.tag == "RichPoint") {
print (hit.collider.transform.position);
}
}
}
I don't know what I am doing wrong,how can I fix it? I want to get the
position of the hited object.
你做错了 3 件事:
1。你没有检查光线投射前鼠标是否被按下。
2。您在打印对象位置之前没有检查 Physics.Raycast
是否击中任何东西。
3。您在函数外部定义了 hit
变量。这不是一个好主意,因为它仍然会存储鼠标点击的旧对象。在更新功能中声明。
FIX:
void Update()
{
//Check if mouse is clicked
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
//Get ray from mouse postion
Ray rayCast = Camera.main.ScreenPointToRay(Input.mousePosition);
//Raycast and check if any object is hit
if (Physics.Raycast(rayCast, out hit, jumpMaxDistance))
{
//Check which tag is hit
if (hit.collider.CompareTag("RichPoint"))
{
print(hit.collider.transform.position);
}
}
}
}
无论如何,这个答案是为了告诉你你做错了什么。你应该不使用它。为此使用 Unity 的新 EventSystems
。检查 5.For 3D Object (Mesh Renderer/any 3D Collider) 来自 的答案以正确检测点击的方法对象。
所以当我点击游戏中的对象时,我得到了这个错误...
NullReferenceExceptionm:未将对象引用设置为对象的实例 JumpDestination.Update () (在 Assets/Scripts/JumpDestination.cs.:12)
我不知道我做错了什么,我该如何解决? 我想获取被击中物体的位置
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JumpDestination : MonoBehaviour {
private RaycastHit hit;
public float jumpMaxDistance;
void Update(){
Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit, jumpMaxDistance);
if (hit.collider.gameObject.tag == "RichPoint") {
print (hit.collider.transform.position);
}
}
}
I don't know what I am doing wrong,how can I fix it? I want to get the position of the hited object.
你做错了 3 件事:
1。你没有检查光线投射前鼠标是否被按下。
2。您在打印对象位置之前没有检查 Physics.Raycast
是否击中任何东西。
3。您在函数外部定义了 hit
变量。这不是一个好主意,因为它仍然会存储鼠标点击的旧对象。在更新功能中声明。
FIX:
void Update()
{
//Check if mouse is clicked
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
//Get ray from mouse postion
Ray rayCast = Camera.main.ScreenPointToRay(Input.mousePosition);
//Raycast and check if any object is hit
if (Physics.Raycast(rayCast, out hit, jumpMaxDistance))
{
//Check which tag is hit
if (hit.collider.CompareTag("RichPoint"))
{
print(hit.collider.transform.position);
}
}
}
}
无论如何,这个答案是为了告诉你你做错了什么。你应该不使用它。为此使用 Unity 的新 EventSystems
。检查 5.For 3D Object (Mesh Renderer/any 3D Collider) 来自