【发布时间】:2020-02-12 13:12:42
【问题描述】:
问题:
如何检查 MonoBehaviour 的公共游戏对象是否已在检查器中分配 Unity3D,因为 null
(object==null)的比较失败。
具体例子:
我即将为 Unity3D 编写一个通用方法,它可以在任何可为空的对象上调用。它检查对象是否为空,如果是,则写入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 似乎不为空,但它也无法使用,因为它没有被分配。在这种情况下,控制台输出为:
错误
空
为什么(myObject == null) 是假的,而Debug.Log(testObject) 给我null 只要相应的对象没有在统一检查器中分配。
编辑/解决方案: 感谢 derHugo 的帮助,我最终得到了这个通用代码 sn-p:
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;
}
}
【问题讨论】: