Home > Back-end >  Why Unity RayCastHit cant CompareTag
Why Unity RayCastHit cant CompareTag

Time:06-22

I want to make crosshair ingame to detect button, so most tutorials suggesting using RaycastHit.

I can't make RaycastHit to detect CompareTag whatever i did. I tried using Collider and the result still the same.

Here's the code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class MainMenu : MonoBehaviour
{
    private RaycastHit _hit;

    public int distanceofRaycast = 10;

    public Camera playerCamera;

    void Update()
    {
        Ray ray = playerCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));

        if(Physics.Raycast(ray, out _hit, distanceofRaycast))
        {
            if(Input.GetButtonDown("Fire1") && _hit.transform.CompareTag("StartButton"))
            {
                Debug.Log("Start");
                Play();                
            }
            else if(Input.GetButtonDown("Fire1") && _hit.transform.CompareTag("QuitButton"))
            {
                Debug.Log("Quit");
                Quit(); 
            }
        }
    }

    public void Play()
    {
        SceneManager.LoadScene("set01");
    }

    public void Quit()
    {
        Application.Quit();
    }
}

CodePudding user response:

_hit.transform is pointing to the rigidbody, if present, hit.collider.transform is the actual transform that has the Collider component attached, that was hit (and this can be a child in your hierarchy)

hit.transform vs hit.collider

Did you tag the correct transform?

To debug your problem, I suggest to add this debug log, so you see what you hover over:

 if (Physics.Raycast(ray, out _hit, distanceofRaycast))
 {
     String tr_name = _hit.transform.name;
     String tr_tag = _hit.transform.tag;
     String col_name = _hit.collider.transform.name;
     String col_tag = _hit.collider.transform.tag;
     Debug.Log("hit this object:"   tr_name   " (tag: "   tr_tag   "), on this collider: "   col_name   "(tag: "   col_tag   ")");
 }

This should log without pressing a Mousebutton, so you can see if the objects you hit print the correct tags.

  • Related