前言
这篇博文的起因还得追溯到我在学习UGUI源码时遇到的“奇怪”代码:
public abstract class UIBehaviour : MonoBehaviour
{
// Other code...
public bool IsDestroyed()
{
// Workaround for Unity native side of the object
return this == null;
}
}
当时我很诧异为什么需要专门写一个方法来执行这么简单的运算,所以就查阅了一些相关资料,结果发现了一些有趣的事,甚至让我想起曾经怎么也查不出来的Bug是怎么发生的。
本来参考了以下几篇博文:
Custom == operator, should we keep it?
Checking for null references in Unity
Unity 自定义的 == 操作符
如果你翻看过 UnityEngine.Object
中的API,会发现其中悄咪咪的对 “==” 进行过重载操作:
namespace UnityEngine
{
public class Object
{
// Other code...
public static bool operator ==(Object x, Object y);
}
}
注意!这里所有的
Ob