Stop null checking every GetComponent

One call does the check for you.

Stop null checking every GetComponent

The problem

Fetch, then hope.

void OnTriggerEnter(Collider other){    var hp = other.GetComponent<Health>();    if (hp != null)        hp.Take(10);}

Unity's null is not a plain null. Comparing it runs a managed to native check every time.

The fix

TryGetComponent says yes or no.

void OnTriggerEnter(Collider other){    if (other.TryGetComponent(out Health hp))        hp.Take(10);}

It returns a plain bool and never allocates when the component is missing.

Why the old one allocated

A miss used to cost memory.

CallFoundMissing
GetComponentreturns itallocates in the editor
TryGetComponentreturns itfalse, nothing allocated

In the editor the miss path built a warning object. In a trigger firing every frame that is garbage.

The rule

If you might not find it, use Try.

Always there
cache it in Awake
Might be there
TryGetComponent
Never in Update
a raw GetComponent

out declares it inside the if, where it is safe.