- Home /
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
}
}
Answer by Mouton · Jun 06, 2015 at 03:41 PM
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.
Awesome! I ended up switching component == null
to component.Equals(null)
. Are there any unwanted side effects from this?
There are, but it depends of your needs. If somebody (you, Unity developpers, or any pluggin you use) decide to override the Equals method of the Type you try to pass, the new method will get called, resulting in undesired behaviour.
Yet, if you know that it will never happen, there is no issue with it.
For more security, you can use the Generic comparer:
if (EqualityComparer<ComponentType>.Default.Equals(component, default(ComponentType)))
{
// [...]
}
For further details, look at this answer.
Your answer
![](https://koobas.hobune.stream/wayback/20220613200711im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Collision triggers do not work on child gameobject 3 Answers
GetComponent keeps returning null 3 Answers
Problem with jumping in fps game 1 Answer