【问题标题】:Why is my Rigidbody != null immediately after seeing that it is null?为什么我的刚体 != 在看到它为空后立即为空?
【发布时间】:2015-06-06 15:30:17
【问题描述】:

我正在检查“我的游戏对象”是否有刚体。它不是。但是,尽管刚被证明为 null,但对 Rigidbody 进行 null 检查的条件失败了。

为什么会这样?如何让我的条件块运行?

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
    }

}

【问题讨论】:

    标签: c# generics unity3d null


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      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
          }
      
      }
      

      【讨论】:

        【解决方案3】:

        很确定 gameObject.GetComponent() 不会返回 null。它必须返回一个对象,该对象具有返回“null”的 .ToString() 方法。 如果它实际上是 null 的结果

        "Component is " + component 
        

        将是“组件是”,因为 null 将是字符串连接中的空字符串。

        能否调试代码并设置断点以查看 GetComponent 返回的内容?在您的即时窗口或本地窗口中检查它。

        【讨论】:

          猜你喜欢
          • 2013-10-29
          • 2016-04-09
          • 2014-06-05
          • 2022-11-29
          • 2021-12-30
          • 1970-01-01
          • 2021-06-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多