Null check not work for GameObject sometimes

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cubesky/article/details/54970565

Example Code:

void Test(object obj)
{
    if (obj == null) {
       return;
    }
}

When the obj is an instance of GameObject, the null check will failed.

Reason

C# operators are overloaded - not overridden. This means that their implementation is determined at compile time - not runtime, and so is decided by the type of the reference - not the object being referenced.

In your case you are doing a null check on a variable of type object, which will invoke the == operator as defined for System.Object, the functionality of which is to check if the actual reference is equal to null, which it will not be for a reference to a destroyed GameObject.

To achieve the functionality you want, you need to also perform a null check with a reference of type GameObject, thus invoking the == operator as defined for GameObject, the functionality of which is to also equal null if the GameObject has been destroyed.

One example could be:

Code (csharp):
  1. if( obj ==null || (obj is GameObject && (GameObject)obj == null ) )continue;

Or (Because Equals method is overriden) :

obj ==null||obj.Equals(null)


https://forum.unity3d.com/threads/there-is-a-gameobject-is-in-a-stack-how-to-detect-if-it-has-been-destroyed.253196/

阅读更多

没有更多推荐了,返回首页