Null-Safe GetComponent Call in Unity

Daniele Quero, PhD
Towards Dev
Published in
3 min readDec 14, 2021

--

Objective: use the well-known GetComponent method in a new, null-safe way

In this tutorial, I’m going to show you a simple idea to avoid writing the same 2 lines of code over and over again.

Many times we use the GetComponent method to grab a reference to a Component attached to a game object, usually the same game object to which our script is attached.

For many reasons (inattention, dynamic stuff going on…), this method may return null, meaning that no component of the specific type wasfound.

--

--

A professional developer with passion for game developing and skill-growing. A former Nuclear Physics Researcher who changed his life to pursue his dreams