Question by
Naiveca · Sep 05, 2021 at 02:53 AM ·
gameobjectraycasting
How to check if raycast hits a certain object?
I want to open an UI element when raycast hits a certain object. I've gotten to a point where it works if the raycast hits any object, but not from a certain object. I've tried it with tags, but couldn't get it to work either.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OnClickDestroy : MonoBehaviour
{
public GameObject Trader;
public void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, 2))
{
//Here it stops working, this line doesn't do anything
if (gameObject == Trader)
{
Destroy(Trader);
}
}
}
}
}
Comment
Made it work with this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OnClickDestroy : MonoBehaviour
{
public GameObject Trader;
public void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.tag == "Trader")
{
Destroy(Trader);
}
}
}
}
}
Best Answer
Answer by Naiveca · Sep 05, 2021 at 05:38 AM
Made it work with this using System.Collections; using System.Collections.Generic; using UnityEngine;
public class OnClickDestroy : MonoBehaviour
{
public GameObject Trader;
public void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.tag == "Trader")
{
Destroy(Trader);
}
}
}
}
}
Answer by rage_co · Sep 05, 2021 at 04:08 AM
Physics.Raycast is just a simple boolean value, and hence doesn't return any info on what it has hit, you should be looking for Physics.RaycastHit, more precisely the collider property, which you can use to get the gameObject it hit