问题:
如何在Unity3D中检查MonoBehaviour的公共gameObject是否已经在检视面板中分配,因为空值比较
(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似乎不为空,但它也无法使用,因为它未被分配。在这种情况下,控制台输出如下:
False null
当相应的对象未在Unity检查器中分配时,为什么(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;
}
}