Hey guys I am new for unity, Is there any difference between these?
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:
GetComponent<player>();
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.