name of object hit

Could anyone advise on how I can get the name of an object hit using RayCastHit? RayCastHit returns all the physical information I need about the object hit but how can I access the freetext ‘.name’ information? Alternatively, what can I access about an object hit wih RayCastHit to uniquely identify it as a gameObject in my hierarchy view? I want this info to provide textual user feedback about what an object --either the player himself or another object–can “see”, I understand that I could use Physics.LineCast to answer the question “Can this object see that object?”, but I’m approaching this more generally with “What can the object see?” and thought RayCastHit was the way to go.

I also have a second vaguely-related question. I see from the Unity 3D platform tutorial that an EnemyPoliceGuy identifies the player object to attack using the GameObject.FindWithTag(“player”). Is this recommended over GameObject.Find(“player”) --in the case where the object has a “player” tag and a “player” name – and, if it is, why?

Many thanks

Well, the name is easily fetched:

var name : String = hit.gameObject.name;

So you can access the object hit directly :slight_smile:

The GameObject.FindWithTag(“player”) is faster than GameObject.Find(“player”) since it doesn’t have to match a string with every GameObject

Fantastic, Doleman. Thank you so much.

Doleman I tried your suggestion (with gameObject and GameObject) but I get this error message:
error BCE0019: ‘gameObject’ is not a member of ‘UnityEngine.RaycastHit’
Here’s my trial script based on the documentation example but it won’t run with the third line. ???

Oh sorry, my bad! :frowning:

You need to get it via the transform…

hit.transform.gameObject.name

The Raycast function fills out the ‘hit’ variable with the relevant information, so you can’t set the value of hitObjectName from it until after that has happened.

So nice. That works a treat now, Doleman. Excellent. Thanks also, Neil.