20170613 判断gameobject为空 - talesten/UnityStep GitHub Wiki
项目开发时,用到一个对给定gameobject插值变色的逻辑,但是gameobject可能在调用前已经销毁.这时调用肯定会空引用,但是加入if(null==obj)
判断也会报错:
MissingReferenceException: The object of type `GameObject` has been destroyed but you are still trying to access it.
解释:
gameobject被销毁会调用绑定脚本的OnDestroy方法。 在所绑定的脚本里不能用if(null == gameObject)或者if(null == transform)这样判断,这时对象已被销毁,不可继续访问,会报这个错>MissingReferenceException
解决办法:
- 在脚本内部判断
if(null == this)
- 使用
GameObject.Find
OnDestroy
里注册回调
觉得以上方法都不是很方便.最后自己想到个简单的办法.首先将gameobject放入list中管理.删除时给调用方法返回一个bool值作为判断
if (0 == gourpArray[i].hitPoint)
{
removeGameObjectInGourpArray(gourpArray, gourpArray[i]);
return true;
}