If hit tag with Raycast

I want to detect hit with a gameObject when I click on it with my mouse,

I’m using raycast and C#

using UnityEngine;
using System.Collections;


class ButtonTest : MonoBehaviour
{
    public Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    public void Update()
    {
        if (Input.GetButton("Fire1"))
        {
            if (Physics.Raycast(ray, 100))
                print("Hit something");


        }
    }
}

1 Answer

1

Ray ray is only calculated when ButtonTest is initialized. You want to put that code in the update when the click actually happens instead.

After that’s solved you need to use the RaycastHit class as an out parameter to your ray cast.

void Update() {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, -Vector3.up, out hit))
            if(hit.transform.tag == "someTag") {
            }
        
    }