if (o.GetComponent<Something>()!=null)
o.GetComponent<Something>().foo()
The issue with this, is that GetComponent throws an error in this case?
Which has a perofrmance penalty?
So I should test it with TryGetComponent, instead of GetComponent?
Also, is there a way to the test without having to porvide a variable for “out”?
"TryGetComponent attempts to retrieve the component of the given type. The notable difference compared to [GameObject.GetComponent](https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html) is that this method does not allocate in the Editor when the requested component does not exist."
Look at the code example. Ignore the variable if you don’t want to actually use it. You can declare it inline to the call.
You can discard the out value with “_” as seen in Microsoft’s C# docs.
There are a few valid and equivalent ways to call TryGetComponent here:
// can specify generic type argument
o.TryGetComponent<ComponentType>(out _);
// can specify out argument's type without making a local variable
o.TryGetComponent(out ComponentType _);
// doing both is redundant, but valid
o.TryGetComponent<ComponentType>(out ComponentType _);
There’s no need to test for the presence of a component if you’re confident that it’s always going to be present in the final build.
Some coders will always check for components but it’s not really necessary as you’ll get an error if it isn’t present and that’s a good thing because then you can fix it. What’s worse is checking for a component and not getting an error because you failed to notify yourself of its absence.
In some situations checking for components is obviously necessary because your program will treat a gameObject differently depending on which components are present.
Since you are concerned about negligible performance effects, you’ll welcome this change.
While it does little to performance it’s less negligible than the null check. But most importantly this change provides significant benefits to readability and maintainability:
var something = o.GetComponent<Something>();
if (something != null)
something.foo();
There was a post not too long ago where someone profiled GetComponent vs. TryGetComponent, and found TryGetComponent was notably faster in both build and the editor.
I pretty much only use TryGetComponent these days.