Null check not work for GameObject sometimes

来源:互联网 发布:linux rpm安装目录 编辑:程序博客网 时间:2024/06/02 06:53

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/

0 0
原创粉丝点击