Im mostly new to Unity and C#, so I’m just curious.
2 Answers
2GetComponent<SomeComponentName>()
is just faster than
GetComponent( "SomeComponentName" )
GetComponent( typeof(SomeComponentName) )
so prefer it by default. The End.
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.
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.
– b4guw1x
How come its faster? Also I said GetComponent(SomeComponentName); and not GetComponent(typeof(SomeComponentName));
– ChintufpThere is no such thing as
– andrew-lukasikGetComponent(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).
– andrew-lukasikThanks for the help
– ChintufpOf course, the string overload still exists. Nobody should use it, but saying there is no such thing is simply incorrect.
– FlaSh-G