NullReferenceException because the Rigidbody was missing?

Make Unity add it for you.

NullReferenceException because the Rigidbody was missing?

The problem

Assuming it's there.

public class Mover : MonoBehaviour{    void Start()    {        GetComponent<Rigidbody>().useGravity = false;    }}

No Rigidbody on the GameObject? GetComponent returns null and this line throws.

The fix

Declare what you need.

[RequireComponent] tells Unity this script can't work without another component.

[RequireComponent]→added automatically

The fix in code

One attribute.

[RequireComponent( typeof( Rigidbody ) )]public class Mover : MonoBehaviour{    void Start()    {        GetComponent<Rigidbody>().useGravity = false;    }}

Add Mover and Unity adds a Rigidbody too. It won't let you remove it while Mover needs it.

Watch out

It only runs when you add the script.

Objects that already had Mover before you added the attribute won't get a Rigidbody.

New objects
component added ✓
Existing objects
re-add the script

The rule

Declare dependencies. Skip the null checks.

Needs a component
[RequireComponent]
Unity adds it
with the script
Old objects
re-add the script