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)

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页