简体   繁体   English

Unity-当场景中有多个预制件时,Raycast无法正常工作

[英]Unity - Raycast not working when more than one prefab on Scene

I created a script that uses RayCasting for detecting two Prefabs - One prefab has a tag called "target" and the second prefab has a tag called "unTarget". 我创建了一个脚本,该脚本使用RayCasting检测两个预制件-一个预制件具有名为“ target”的标签,第二个预制件具有名为“ unTarget”的标签。 On click on prefab 1 with "Target" tag its supposed to increment count and when clicking on prefab 2 with "unTarget" tag its supposed to decrement the count. 在点击带有“ Target”标签的预制件1时,它应该增加计数;当点击带有“ unTarget”标签的预制件2时,它应该减少计数。 This seems to work when only one Prefab is in the scene. 当现场只有一个预制件时,这似乎可行。 It will increment/decrement when only one is added and clicked. 当仅添加和单击一个按钮时,它将递增/递减。 When both prefabs are in the Scene both prefabs will increment. 当两个预制件都在场景中时,两个预制件都将增加。 I am not sure why this is happening. 我不确定为什么会这样。 Any Help or Ideas? 任何帮助或想法? Sorry if my code is a bit messy. 抱歉,我的代码有点混乱。

using UnityEngine;
using System.Collections;

public class clicks : MonoBehaviour 
{

    public int score;  

    void Start()
    {
        score = 0;
    }

    // Update is called once per frame
    void Update() 
    { 
        if (Input.GetMouseButtonDown (0)) 
        {

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit,200))
            {
                if (GameObject.FindGameObjectWithTag ("target"))
                {
                    score++;
                }
                else 
                {
                    score--;
                }
            }
      }
}   

The GameObject.FindGameObjectWithTag method is going to look at your entire scene for an object with target as the tag. GameObject.FindGameObjectWithTag方法将在整个场景中查看target为标签的对象。 Since you have one in the scene that will always return true, if you hit something. 由于您在场景中碰到某物,因此总是会返回true。

You need to look at the properties on the RaycastHit and pull the tag from there. 您需要查看RaycastHit上的属性,然后从那里拉标签。

if (hit.collider.tag == "target") 
{
   score++;
} 
else 
{
   score--;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM