One C# operator replaces three lines.

The problem
Three lines to set a default.
if ( _target == null ){ _target = FindTarget();}
Check for null, then assign. It works, but you write it everywhere and it buries what you meant.
The fix
Assign only if it's null.
C# has an operator for exactly this: ??= . It assigns the right side only when the left side is null.
_target??=FindTarget()
If _target already has a value, nothing happens.
The fix in code
One line.
protected override void OnUpdate(){ _target ??= FindTarget();}
FindTarget only runs while _target is null. Once it's set, the line does nothing.
Its sibling
?? picks a fallback.
string name = player.Nickname ?? "Guest";?? gives you the left side, or the right side if the left is null.
Watch out in Unity
Destroyed objects aren't null to ??.
Unity makes a destroyed object equal null with ==, but ?? and ??= skip that check.
- Plain C# objects
- ?? and ??= are safe
- Unity Objects
- use if ( x == null )
The rule
Let C# write the null check.
- Assign if null
- x ??= value
- Fallback
- x ?? value
- Unity objects
- x == null