为什么我的Rigidbody != null 看到它是null 之后马上就变成null 了?

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

我正在检查 "My Game Object" 是否有刚体。它不是。但是,尽管刚刚被证明是空的,但对 Rigidbody 进行空检查的条件失败了。

为什么会这样?我怎样才能使我的条件块 运行?

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
    }

}

null 对象引用未格式化为 "null"。它们格式化为空字符串。 component 不为空。它的 ToString 输出是 "null".

来自其他研究 (Equals(item, null) or item == null and Unity Forums) 并详细说明 usr 的回答:

我需要保证在我的 CheckIfNull header 中传递了一个组件。更新后的代码如下所示:

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
    }

}

很确定 gameObject.GetComponent() 不会 return 为空。它必须 return 一个具有 returns "null" .ToString() 方法的对象。 如果它实际上是 null

的结果
"Component is " + component 

将是 "Component is" 因为 null 在字符串连接中将是一个空字符串。

能否调试一下代码,打个断点看看GetComponentreturn是什么?在您的 Immediate window 或 Locals window.

中查看