Unity3d中UnityEngine.Object的几个注意点

UnityEngine.Object继承自system.Object,是Unity所涉及所有物体的基类。

先看一下Object重载的运算符:

Operators
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.

posted on 2013-12-11 18:07  焰企鹅  阅读(10318)  评论(0编辑  收藏  举报