How come we don't use GetComponent(someComponent); instead of GetComponent<someComponent>();

Im mostly new to Unity and C#, so I’m just curious.

2 Answers

2

GetComponent<SomeComponentName>()
is just faster than
GetComponent( "SomeComponentName" )
GetComponent( typeof(SomeComponentName) )
so prefer it by default. The End.

How come its faster? Also I said GetComponent(SomeComponentName); and not GetComponent(typeof(SomeComponentName));

–

There is no such thing as GetComponent(SomeComponentName);

–

Generics are faster because part of their code is evaluated (work done) at compilation time (when you build an exe file) and not at execution time (when game is played).

–

Thanks for the help

–

Of course, the string overload still exists. Nobody should use it, but saying there is no such thing is simply incorrect.

–

Hi,

Because of something called Generic, or Template

Unity’s GetComponent() method is a Generic that will try to return the type you added as the generic type T in GetComponent<T>(). T must be a Component.

Writing something inside the parenthesis of a method call will be interpreted as a stack-allocated object reference that must be inspected at code execution time where generics does that at compilation time.
Therefore, you want to use generics.

could you please explain it in simpler terms? Thanks

–

I legit understood nothing from the link. :(

–

Imagine that you write a function to get first element of lists and it takes an intiger list as an argument. But what about the other types of lists? like float list? You would like to implement it to all of the components and you would rewrite for each. But there is a type called generic. And with that you can have a func like GetFirstElement(List<T> listRef) and you can use it with all of the types. Get component is used for all types of elements. There fore it writen with generic syntax.

–