Null Components and You

Do you use the null coalescing operator?? If so, be careful about using it with properties of MonoBehaviour that return a component. For example, if you have an object with no rigidbody attached, the following example will not in fact add a rigidbody:

Rigidbody rb = rigidbody ?? gameObject.AddComponent<Rigidbody>();

Why? For some reason, these built-in properties (such as rigidbody, collider, and so on), actual return an object of the appropriate type that evaluates to null, rather than an actual null reference, even when the component does not exist. For example, on an object with no rigidbody, this line will log true:


On the other hand, this example will throw a NullReferenceException, as expected:

Rigidbody rb = GetComponent<Rigidbody>();

As such, you can rewrite the first example in the following way and it should work:

Rigidbody rb = GetComponent<Rigidbody>() ?? gameObject.AddComponent<Rigidbody>();

2 thoughts on “Null Components and You”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.