0
\$\begingroup\$

Hello im new to unity and im learning raycast right now , after checking the documentation here https://docs.unity3d.com/ScriptReference/RaycastHit-triangleIndex.html , i got something that's confusing me , what is the difference between :

 MeshCollider themeshhit = thehit.collider as MeshCollider;
 //
 if (themeshhit == null) {
 Debug.Log (" | themeshhit == null ! | ");
 }   
 //    

and :

 MeshCollider themeshhittwo =  thehit.collider.gameObject.GetComponent<MeshCollider> ();
 //
 if (themeshhittwo == null) {
 Debug.Log (" | themeshhittwo == null ! | ");
 } 
 //  

Both method is working correctly , but i want to know what is the difference between them , and i also want to know which one is better if comparing against speed , compatibility , and ability .

Edit : variable thehit is look similar to this

 RaycastHit thehit;
\$\endgroup\$
4
\$\begingroup\$

The correct way to do what you want is the first one :

 MeshCollider theMeshHit = thehit.collider as MeshCollider;

In contrary to simple gameobjects .collider does not call GetComponent when using RaycastHit. The reference of the collider is stored in the object when the Physics.Raycast is called, and .collider is the getter to this collider.

The 2nd piece of code you tried calls a useless .gameobject make it slower.

TL; DR :

  • thehit.collider.gameObject.GetComponent<MeshCollider> (); : 1 call to GetComponent + 1 call to .gameobject
  • thehit.collider as MeshCollider : 1 cast used
\$\endgroup\$
  • \$\begingroup\$ okay thanks for the warn but this is not answering my question , i still upvote it because this is important . \$\endgroup\$ – user6668201 Mar 12 '17 at 7:25
  • \$\begingroup\$ I edited my answer with additional information. \$\endgroup\$ – Hellium Mar 12 '17 at 7:28
  • \$\begingroup\$ i disagree you said "using the as keyword is not needed" because its working ( and shorter ) , also i don't understand how i call "GetComponent<>()" twice in my second code . Edit : maybe you can explain why i should not use "as" and tell me the difference between "as" and "GetComponent<>()" \$\endgroup\$ – user6668201 Mar 12 '17 at 7:30
  • 1
    \$\begingroup\$ Calling GetComponent <MeshCollider>() already returns a MeshCollider object, thus, you don't need to cast using the as keyword. I already said that thehit.collider is the (bad) shorthand to thehit.GetComponent <Collider>, thus, when you write thehit.collider.gameObject.GetComponent<MeshCollider> (); you call GetComponent twice. \$\endgroup\$ – Hellium Mar 12 '17 at 7:35
  • \$\begingroup\$ okay that's clear enough , using "GetComponent<>()" is faster and shorter . but is there any special ability at each method ? \$\endgroup\$ – user6668201 Mar 12 '17 at 7:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.