Why is my Rigidbody != null immediately after seeing that is null?

I am checking to see if “My Game Object” has a Rigidbody. It does not. But the conditional for the null check on Rigidbody fails, despite having just been proven null.

Why is this happening? How can I make my condition block run?

using UnityEngine;
using System.Collections;

public class NullChecker : MonoBehaviour
{

    void Start()
    {
        GameObject go = GameObject.Find("My Game Object");
        CheckIfNull<Rigidbody>(go);
    }

    public void CheckIfNull<ComponentType>(GameObject gameObject)
    {
        ComponentType component = gameObject.GetComponent<ComponentType>();
        Debug.Log("Component is " + component); //"Component is null"
        if (component == null)
        {
            Debug.Log("Inside null check"); //Never prints
        }
        Debug.Log("Finished null check"); //Does print
    }

}

Because your generic type “ComponentType” is not Unity-nullable, as it can pass non-nullable types (you can pass a struct, which is a non-nullable type).

You need to change

public void CheckIfNull<ComponentType>(GameObject gameObject)

with

public void CheckIfNull<ComponentType>(GameObject gameObject) where ComponentType : Component

If you want you generic to allow non-nullable type, you can do this

Change

if (component == null) // Doesn't work

with

if (component.GetType() == typeof(ComponentType)) // Works

Hope this helps !

[Edit:] Since you are testing for a component, you should use this syntax:

public void CheckIfNull<ComponentType>(GameObject gameObject) where ComponentType : Component

Otherwise, you could pass any type, even something which is not a component, like an int.

CheckIfNull<int>(go); // the compiler won't warn, it will result in an ArgumentException

You will be able to pass MonoBehaviours too, as they derive from Component.