- Home /
The question is answered, right answer was accepted
GetComponent vs TryGetComponent
I know what is a difference between GetComponent and TryGetComponent methods and as I understand the second one is better to avoid allocate memory. But are there situations where GetComponent is better or we just can't use TryGetComponent? I'm asking because if TryGetComponent is just better and there is no reason to not use it, then what's the case to use GetComponent?
Since TryGetComponent<>() was new as of the 2019 release, you can safely think of GetComponent<>() as a legacy feature to support older codebases so they don't break when they're imported to newer versions of the editor.
That said, some people are set in their ways, so they're just going to keep using GetComponent anyhow, and there really isn't a compelling reason not to keep supporting that function, so essentially it's just giving you a choice of which to use, one of which has a negligible performance boost but might be more efficient to write out once you get used to it.
TL;DR: It comes down to personal preference, but TryGetComponent is probably the best practice to incorporate going forward.
Answer by perf401 · Feb 06 at 12:51 PM
Not an expert, but I think memory allocation is happening only in the Editor. But yeah it's fine to always use TryGetComponent, i don't think there any situations where Get component is better.