1

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
    }

}
Evorlor
  • 7,263
  • 17
  • 70
  • 141

3 Answers3

1

null object references to not format as "null". They format as an empty string. component was not null. It's ToString output was "null".

usr
  • 168,620
  • 35
  • 240
  • 369
0

From other research (Equals(item, null) or item == null and Unity Forums) and to elaborate on usr's answer:

I needed to guarantee that a Component was being passed through in my CheckIfNull header. The updated code looks like this:

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) where ComponentType : Component
    {
        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
    }

}
Community
  • 1
  • 1
Evorlor
  • 7,263
  • 17
  • 70
  • 141
0

Pretty sure gameObject.GetComponent() doesn't return null. It has to return an object that has a .ToString() method that returns "null". If it actually was null the result of

"Component is " + component 

would be "Component is" because null will be an empty string in string concatenation.

Can you debug the code and set a breakpoint to see what GetComponent returns? Check it in your Immediate window or your Locals window.

Dacker
  • 892
  • 2
  • 8
  • 12