# Unity using “as” vs “GetComponent<>()”

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;


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
• okay thanks for the warn but this is not answering my question , i still upvote it because this is important . – user6668201 Mar 12 '17 at 7:25
• I edited my answer with additional information. – Hellium Mar 12 '17 at 7:28
• 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<>()" – user6668201 Mar 12 '17 at 7:30
• 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. – Hellium Mar 12 '17 at 7:35
• okay that's clear enough , using "GetComponent<>()" is faster and shorter . but is there any special ability at each method ? – user6668201 Mar 12 '17 at 7:44