Search Unity

Accessing mesh filter

Discussion in 'Scripting' started by tibor698, Jan 12, 2014.

  1. tibor698

    tibor698

    Joined:
    Nov 26, 2012
    Posts:
    84
    In Unity 3D doc for accessing vertices there is a line in C#:

    Code (csharp):
    1. Mesh mesh = GetComponent<MeshFilter>().mesh;
    I have tried to access it with Mesh mesh = GetComponent("MeshFilter").mesh but it wont work. This is the way I used before to access object components.
    Why do I have to put <MeshFilter>() ? What is the meaning of this method ?
     
  2. Tiki

    Tiki

    Joined:
    Mar 3, 2013
    Posts:
    299
  3. tibor698

    tibor698

    Joined:
    Nov 26, 2012
    Posts:
    84
    Yea but why we have to put <> ? Why not just use GetComponent("MeshFilter") ?
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You pretty much never want to use strings in GetComponent. In Unityscript you would write GetComponent(MeshFilter), which casts to MeshFilter automatically. If you wrote GetComponent("MeshFilter"), it would cast to Component, which isn't what you want. In C# you could write GetComponent(typeof(MeshFilter)) as MeshFilter, which is quite annoying, so GetComponent<MeshFilter>() is a shortcut that uses generics to do the casting. (Although it does run a tiny bit slower than manually casting, nothing to be concerned about though. But that's why you should not use the generic version of GetComponent in Unityscript, since it's slightly less efficient and in the case of Unityscript doesn't save you any typing, in fact the opposite.)

    --Eric