Search Unity

GetComponent<Script>() or GetComponent(Script) ?

Discussion in 'Getting Started' started by e001010011100101110111, Aug 3, 2021.

  1. e001010011100101110111

    e001010011100101110111

    Joined:
    Aug 3, 2021
    Posts:
    1
    Hey guys I am new for unity, Is there any difference between these?
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    The first one gets a component by type, while the second gets a component by name.

    They both do the exact same thing, but you should use the first one pretty much 100% of the time to avoid string comparison errors.

    Imagine you have a script named "Player" and you make a mistake when referencing it like so:
    Code (CSharp):
    1. GetComponent<player>();
    2. GetComponent("player");
    The first version will not even compile, and you'll get an error right away letting you know that "player" doesn't exist (as the script does not start with a lowercase 'p');

    The second version will compile just fine, however. You won't get any error until you actually run the application instead.

    Now, image you wanted to change the name of your script.
    If you use your code editor's rename tool to do so, then it will also be changed everywhere
    GetComponent<Player>()
    is used, but not anywhere
    GetComponent("Player")
    is used, meaning you'd have to manually update the name everywhere else in your entire application, which is a nightmare to deal with.