【发布时间】:2019-09-24 11:48:10
【问题描述】:
我有一个特殊的函数,它可以将object 作为参数。这样它既可以是 MonoBehaviour 也可以是 GameObject:
奇怪的是,当我将 null GameObject 转换为 Object 时,它不再显示为 null:
public class EquipmentSlots : MonoBehaviour {
// This is null: it hasn't been set in the inspector
public GameObject offHandEquipLocation;
void Start () {
Validation.RequireField(
"offHandEquipLocation",
offHandEquipLocation
)
}
}
public class Validation : MonoBehaviour {
public static void RequireField(string name, object field) {
if (field == null) {
Debug.Log($"{name} field is unset");
}
}
}
Log 调用永远不会在这里运行,因为对象不为空。
如果我将Debug.Log(offHandEquipLocation == null) 放入Start() 函数中,它会打印出true。如果我将Debug.Log(field == null) 放在RequireField() 方法中,它会打印false。
有没有办法可以查看object 是否为空?
【问题讨论】:
-
不要使用
== null,而是使用bool运算符if(field) -
@derHugo 无法做到这一点,因为
field是object,因此不能以这种方式使用。我知道有解决方法,我真的只是想了解为什么我会看到这种行为。 -
@derHugo 我想看看是否有一种方法可以只更改
RequireField()方法来完成这项工作,因为实际上有很多像这样的Start()函数,而且工作量更大全部更改。 -
那你为什么将它传递为
object?如果它是GameObject类型,则使用Object(UnityEngine.Object) ... Unity 有overwritten 他bahvior 用于== null类型Object(基本上所有Unity 内置类型) -
您可能对my answer here 感兴趣,关于确定为什么某个参考是
null;)