【解决】MissingReferenceException: The object of type ‘GameObject‘ has been destroyed 观察者模式 监听物体被销毁

MissingReferenceException: The object of type ‘Text’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
该情况发生于我的观察者模式重新加载当前场景时 监听的物体被销毁
如上所示错误,通过分析,定位到错误是在观察者模式使用事件分发器注册监听 消息。其内部方式使用 委托订阅方式进行,在重加载场景时,unity调用Destory()生命周期函数 此时监听挂载没有被清楚。或者说该监听需要的gameobject 实例重新加载时销毁掉
观察者模式地址
在这里插入图片描述
如下图所示 监听挂载后 在重新加载的过程中没有Remove掉;
在这里插入图片描述
需要在脚本销毁时OnDestroy()生命周期中,调用写好的RemoveEventListener函数(unity在重新加载当前场景时时,会调用该生命周期函数);
在这里插入图片描述
该函数如下所示

public static void RemoveEventListener(string name,UnityAction<object> action)
    {
    
    
        if (eventDic.ContainsKey(name))
        {
    
    
            eventDic[name] -= action;
        }
        Debug.Log("RemoveEventListener");
    }

猜你喜欢

转载自blog.csdn.net/qq_45498613/article/details/129382174
今日推荐