[英]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
So when I am clicking on the object in the game I get this error... 因此,当我在游戏中单击对象时,会出现此错误...
NullReferenceExceptionm : Object reference not set to an instance of an object JumpDestination.Update () (at Assets/Scripts/JumpDestination.cs.:12) NullReferenceExceptionm:对象引用未设置为对象JumpDestination.Update()的实例(位于Assets / Scripts / JumpDestination.cs。:12)
I don't know what I am doing wrong,how can I fix it? 我不知道自己在做什么错,该如何解决? I want to get the position of the hited object. 我想获取命中对象的位置。
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 things you did wrong: 您做错的3件事:
1 .You did not check if mouse is pressed before raycasting. 1。您尚未检查光线投射前是否按下了鼠标。
2 .You did not check if Physics.Raycast
hit anything before printing the object's position. 2。在打印对象的位置之前,您没有检查Physics.Raycast
命中任何东西。
3 .You defined the hit
variable outside a function. 3。您在函数外部定义了hit
变量。 Not a good idea because it will still store the old object the mouse hit. 这不是一个好主意,因为它将仍然存储鼠标所击中的旧对象。 Declare that in the update function. 在更新功能中声明。
FIX : 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);
}
}
}
}
Regardless, this answer was made to show you what you did wrong. 无论如何,此答案都是为了向您显示您做错了什么。 You should not be using this. 您不应该使用此功能。 Use Unity's new EventSystems
for this. 为此,请使用Unity的新EventSystems
。 Check the 5 .For 3D Object (Mesh Renderer/any 3D Collider) from this answer for proper way to detect clicked object. 从检查5。对于3D对象(网渲染/任何3D撞机) 这个答案来检测点击的对象适当的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.