Sometimes when I look at the world, I can see a line behind it.

Null check not work for GameObject sometimes

Example Code:

void Test(object obj)
    if (obj == null) {

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


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://blog.csdn.net/cubesky/article/details/54970565
个人分类: 基础知识
想对作者说点什么? 我来说一句



Null check not work for GameObject sometimes