Null check not work for GameObject sometimes

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/

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值