UnityEngine.Object繼承自system.Object,是Unity所涉及所有物體的基類。
Static Functions 靜態函數 下面的都是靜態函數
Destroy | Removes a gameobject, component or asset. 刪除一個游戲對象、組件或資源 |
DestroyImmediate | Destroys the object obj immediately. You are strongly recommended to use Destroy instead. 立即銷毀物體obj,強烈建議使用Destroy代替。 |
DontDestroyOnLoad | Makes the object target not be destroyed automatically when loading a new scene. 加載新場景的時候使目標對象不被自動銷毀。 |
FindObjectOfType | Returns the first active loaded object of Type type. 返回Type類型第一個激活的加載的對象。 |
FindObjectsOfType | Returns a list of all active loaded objects of Type type. 返回Type類型的所有激活的加載的物體列表。 |
Instantiate | Clones the object original and returns the clone. 克隆原始物體並返回克隆物體。 |
先看一下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
.