UnityEngine.Object繼承自system.Object,是Unity所涉及所有物體的基類。
先看一下Object重載的運算符:
bool | Does the object exist? |
---|---|
operator != | Compares if two objects refer to a different object. |
operator == | Compares if two objects refer to the same. |
下面幾個注意點是我在最近使用發現的。
(1)Object類重載了類型隱式轉換運算符“bool”。這個如果不注意,在某些情況下可能會造成意料外的調用。
例
class Test:MonoBehaviour
{
void Start()
{
Fun(transform);//此函數目的是為了調用 void Fun(system.Object objFlag)
}
void Fun(bool value)
{
Debug.Log("call the bool param fun,the value is:"+value.ToString();)
}
void Fun(system.Object objFlag)
{
Debug.Log("call the param system.Object fun,the value is:"+value.ToString();)
}
}
打印的日志是:call the bool param fun,the value is: true
可以看出,與我們的目的不一致。通過追溯Transform父類,其頂層基類是UnityEngine.Object。這就找到原因了,在這樣的情況下這兩個Fun函數存在調用歧義。transform先被判斷是否存在的引用,然后調用了void Fun(bool value)
建議:同一個類盡量不要使用同名函數,如有要使用同名函數時要特別注意這兩種情況。
(2)Object類重載了類型隱式轉換運算符“==”。這個在與null比較時要特別注意,既使是有效的引用結果有可能是true的。
例:
GameObject go = new GameObject(); Debug.Log (go == null); // false Object obj = new Object(); Debug.Log (obj == null); // true
看一下官方的說明(英文不好翻譯不來):
Instatiating a GameObject adds it to the scene so it's completely initialized (!destroyed). Instantiating a simple UnityEngine.Object has no such semantics, so the it stays in the 'destroyed' state which compares true
to null
.