Using Raycast to detect the name of the hit object?

Hi!
I’m kind of new to Unity and I’m just trying out stuff. For now I’m trying a simple Inventory Script, which I can already use to destroy the gameobject I’ve picked up with “if (ItemHit.transform.CompareTag(“Item”))” . Now, can I get the name of this Object hit by the Raycast? Because all Items are simply tagged “Item”, I can’t differentiate between them. I have already tried “if (ItemHit.collider.name == “conserv_1”)” and “if (ItemHit.collider.gameobject.name == “conserv_1”)”, but it won’t work.

Don’t know if it helps, but here’s the code:

if(Physics.Raycast(transform.position, transform.forward, out ItemHit, range))
{
if (ItemHit.collider.name == “conserv_1”)
{
DidItWork = 1;
}
if (ItemHit.transform.CompareTag(“Item”))
{
Items = Items + 1;
Destroy(ItemHit.transform.gameObject);
}

}

DidItWork always stays 0 here.

Does anyone have an idea?

First of all, use code tags, it makes things easier.

Components’ “name” fields usually just return the name of the component itself (e.g. “BoxCollider”). What you want is the GameObject’s name field, which will give you the name as typed in in the inspector or hierarchy:

if (itemHit.collider.gameObject.name == "conserv_1")

An additional piece of advice, though - comparing against the name of a GameObject is not generally a good idea in terms of making reliable and/or reusable code. If you could give me a little more information about what you’re trying to accomplish I could advise you on what you may want to do instead.

2 Likes