【问题标题】:Unity behavior Property not set in inspector, prints null but doesn't == nullUnity 行为属性未在检查器中设置,打印 null 但不 == null
【发布时间】:2014-02-06 22:51:17
【问题描述】:

我在 MonoBehavior 中有一个属性,定义如下:

public GameObject whatever = null;

我在其中一些上将其设置为实际的 GameObject 引用,而在另一些上将其留空。基本上,它是一个可选属性。现在,当我在程序中测试它时,最疯狂的事情发生了:

Debug.Log(whatever + " " + (whatever == null));

这打印:“null False”。我不知道如何进行。我想要的只是能够在代码中对其进行空测试。 (我也尝试过删除 = null ,但没有任何区别)。 Unity 似乎正在创建一些包装器或其他东西。这是重现问题的完整缩减:

using UnityEngine;
using System.Collections;

public class TestBehavior : MonoBehaviour
{
    public GameObject whatever;

    // Use this for initialization
    void Start ()
    {
       Debug.Log("logical: " + whatever + " " + (whatever == null)); // prints null True
       Print(whatever);
    }

    public void Print<T>(T anObject)
    {
       Debug.Log("Now it gets nuts: " + anObject + " " + (anObject == null)); // prints null False
    }
}

【问题讨论】:

  • null 在连接期间被视为空字符串,因此它应该输出“false”..
  • 另外,您不应该将泛型参数与null 进行比较,请参阅stackoverflow.com/a/864860/238419。不过,这仍然不会导致您看到的问题..

标签: c# unity3d


【解决方案1】:

我在尝试在 Unity 中实例化 Behavior 时遇到了类似的行为 - 在幕后发生了一些不为人知的事情。

对此的快速解决方法可能是引用特定脚本而不是整个游戏对象 - 特别是因为您需要交叉访问的大多数内容都包含在另一个脚本中(例如 HP)或同样可访问(转换, characterController) 如果 whatever 是 MonoBehaviour

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多