Use of RaycastHit

Hello all, why does Rick use “hit.transform.name” to bring back the result of target object name.

Following this website link it says, Transform only finds the tranform of the rigidbody or collider that was hit.
So here, I don’t understand how getting the transform is needed. Unless and its only a guess, the transform is just needed to reach “.name”?
Thanks

Also, would print (hit.collider.gameObject.name); work for this exact same case.

I think it’s just something he chose to do. All components will have a transform, so it’s safe to use it. hit.collider.gameObject.name will work too because all components will have a game object and that will give you the same name. The name is whatever it is called in the hierarchy, so the game object’s name

Hi SHL,

hit.name does not work. Since we want to access the name, we have to access an object that has got the name property. From the list in the API (you linked it), we learn what we are able to access via the RaycastHit object.

C# does not know anything about names or our ideas. All it knows is “exists” and “does not exist”. For this reason, if name is defined in multiple classes and if we are able to access objects of multiple classes, there are multiple ways to access name.

When reading the code without knowing anything about the actual code, the “message” does not always make sense: hit.internet.USA.Europe.transform.gameObject.moon.name could return the name of “your” game object if the objects reference the name of your game objects. C# does not care about the meaning of the names. Nevertheless, we aim to make our code as readable as possible for us humans.

Rick found hit.transform.name more graspable than, for example, hit.collider.gameObject.name. However, that’s a matter of personal preference. Use the code you like best. :slight_smile:


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms