Is there any advantages to using the TryGetComponent version of the check to see if the other collider is a Target? I understand the appeal of less lines of code and a “cleaner” look, but does it make a difference in execution? Also, Nathan said he likes to invert the if statements. Is there an advantage to this? Is this just personal preference? Maybe a good test to see if you are an optimist or a pessimist??
Both GetComponent
and TryGetComponent
are optimised and done in C++ (so I can’t really see exactly how it’s done) but they are probably pretty much the same. The Unity C# code seems to favour TryGetComponent
and it may be a little faster because the checks that you would have to do yourself after GetComponent
are also done in the C++ layer.
Inverting if’s to allow for an early exit is not a bad idea - unless the if becomes some convoluted mess that requires a degree in philosophy to decypher. Exiting early reduces nesting and indentation, which in turn increases readability. Just inverting if’s, however, can reduce readability as well (see my comment on philosophy).
There is, for example, no difference between these apart from the nesting and indentation
void DoSomething(GameObject target)
{
if (target == null) return;
// Do something with target
}
void DoSomethingElse(GameObject target)
{
if (target != null)
{
// Do something with target
}
}
I personally like to exit early whenever I can.
Thanks for the explanation. I guess the early exit would be more efficient if you have a lot of code in the method. Skipping over lines that are not going to be executed makes sense.
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.