Physics2D.Raycast返回null

我有一个问题,让我在这里超级难过。 我将从密钥代码转到鼠标输入 – 然后它变成触摸输入,但首先我想弄清楚为什么我只能用鼠标来做这件事。

我有一个raycast2d设置 – 我希望光线播放能够在屏幕上读取与我的对象的碰撞。 它们只会在它被标记为“猫”的物体时作出反应 – 基本上一旦发生这种情况,猫就会滑出并试图攻击。 但是,它告诉我tagg本身是一个实例化的引用。 但是对象本身默认存在,所以我不知道该怎么做。 这是我的整个脚本。

void Update() { //if ((Input.GetKeyDown(KeyCode.O) && !attacking && attackTimer <= 0)) { if (Input.GetMouseButtonDown(0) && !attacking && attackTimer <= 0) { //every frame check to see if the mouse has been clicked. //Get the mouse position on the screen and send a raycast into the game world from that position. Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);//Vector 2 means only 2 points of axis are read. worldpoint means check the point of the world. Camera is used to determien what we are looking at, and we fill it with our mouse location. RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero); if (hit.collider == null) {//THIS IS THE LINE that says it is having issues. If i REMOVE this line, ANYWHERE i click on the screen activates the cat and thats not what I want to happen. Debug.Log("No Object Touched"); if (hit.collider.CompareTag("Cat")) { GameManager.Instance.AudioSource.PlayOneShot(SoundManager.Instance.Swipe); attacking = true; attackTimer = attackCd; attackTrigger.enabled = true; } 

更新的代码匹配请求的更改:现在获得的错误是NullreferenceException – for:

  if (hit.collider.CompareTag("Cat")) { 

这是我之前获得的相同错误,在使用建议测试的方法程序员重新测试之后。

控制台会告诉我,我没有点击一个对象,然后告诉我null。 所以我想它试图告诉我它没有找到任何标记为场景中存在的猫? 尽管Cat是一个自定义标签,但它被应用于游戏对象即猫 – 与Box对撞机。 它是否需要一种材料或任何东西来阅读它存在? 有没有其他方法可以通过点击其特定位置来调用此对象?

更新:

  Debug.Log("No Object Touched"); if (hit.collider) { if (hit.collider.tag == "cat1") { - 

这摆脱了空引用,但它根本不读猫。 如果我点击猫没有任何反应。 是的,它现在在编辑器中正确标记为“cat1”。 meanign标签 – 新的自定义标签,创建cat1标签。 转到游戏对象,将标签更改为cat1。 还确保打开了colider,触发器。

首先, Physics.RaycastPhysics2D.Raycast是两个不同的东西。

RaycastHit2D返回RaycastHit2D时, Physics.Raycast返回true ,因此在使用Physics2D.Raycast时必须检查null ,否则你将获得NullPointerExceptionexception。

 if (hit == null) { Debug.Log("No Object Hit"); //Return return; } 

我将为diff猫提供diff标签,所以cat,cat1,cat2,cat3。 每个脚本将单独与标签相关联。

但是为什么这样做: if (hit.collider.tag == "Cat")因为你没有提到你有一个名为Cattag

请记住,您列出的cat标签中的C 都没有大写….

那应该是if (hit.collider.tag == "cat" || hit.collider.tag == "cat1" || hit.collider.tag == "cat2" || hit.collider.tag == "cat3")

如果每只猫做不同的东西,那么你应该这样做:

 if (hit == null) { Debug.Log("No Object Hit"); //Return return; } if (hit.collider.CompareTag("cat")) { } else if (hit.collider.CompareTag("cat1")) { } else if (hit.collider.CompareTag("cat2")) { } else if (hit.collider.CompareTag("cat3")) { } 

上面提到的null检查和Cat拼写很可能是造成问题的原因。 请记住,您没有提到您将要开始的错误。

你不知道如何使用标签 ? 看这里

我建议你使用

 hit.collider.CompareTag("Cat") 

代替

 hit.collider.tag == "Cat" 

并确保在编辑器中设置了“Cat”标签

最好首先检查命中是否有碰撞器,然后确认它是您想要比较标记的对象。

  if (hit.collider) { // The hit has a collider if (hit.collider.tag=="Cat") { Debug.Log("Touched it!"); } } 

来自团结论坛: http : //answers.unity3d.com/questions/474523/how-can-i-use-hitgameobjecttag.html