问题:
如何检查MonoBehaviour的公共游戏对象是否已在检查器中分配给Unity3D,因为对空
(object==null)
的比较失败。
具体示例:
我将为Unity3D编写通用方法,可以在任何可为空的对象上调用该方法。它检查对象是否为null,如果为null,则写入Debug.LogError(customMessage)
。该方法如下所示:
public static bool IsNull<T>([CanBeNull] this T myObject, string message = "")
{
if (myObject!= null) return false;
Debug.LogError("The object is null! " + message);
return true;
}
可以在代码中任何位置的任何可空对象上调用该方法,例如在此简单的Monobehaviour中:
public class TestScript : MonoBehaviour
{
public GameObject testObject = null;
public void TestObject()
{
var result = testObject.IsNull("Error message");
Debug.Log(result);
Debug.Log(testObject);
}
}
在大多数情况下,我的方法可以完美地工作,并在编码/调试期间节省了大量时间。但是我现在的问题是,如果我没有在编辑器中签署“ testObject”,则我的测试将无法正常工作,因为testObject似乎不为null,但由于未分配,因此它也不可用。在这种情况下,控制台输出为:
假null
(myObject == null)
为何为假,而Debug.Log(testObject)
给我null
,只要相应的对象尚未在统一检查器中分配。
编辑/解决方案:多亏了derHugo的帮助,我最终得到了以下通用代码段:
public static bool IsNull<T>(this T myObject, string message = "") where T : class
{
switch (myObject)
{
case UnityEngine.Object obj when !obj:
Debug.LogError("The object is null! " + message);
return true;
case null:
Debug.LogError("The object is null! " + message);
return true;
default:
return false;
}
}
即使UnityEngine.Object
的值等于 null
,有时也不是== null
。Object
仍会在其中存储一些元数据,例如您得到一个MissingReferenceException
,而不是通常的NullReferenceException
,因为Unity实施了一些自定义异常,这些异常通常包含why值等于null
的更多详细信息。
特别是因为
public GameObject testObject = null;
是public
字段,它会自动序列化,因此您分配给它的null
值在序列化期间仍将被覆盖。
UnityEngine.Object
派生的[UnityEngine.Object
具有隐式运算符GameObject
对象是否存在?
而不是直接bool
比较,您应该检查
bool
对于适用于任何引用类型的常规方法,您可以例如使用类似的东西
== null