【解决】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 实例重新加载时销毁掉
(观察者模式地址)
【解决】MissingReferenceException: The object of type ‘GameObject‘ has been destroyed 观察者模式 监听物体被销毁_第1张图片
如下图所示 监听挂载后 在重新加载的过程中没有Remove掉;
【解决】MissingReferenceException: The object of type ‘GameObject‘ has been destroyed 观察者模式 监听物体被销毁_第2张图片
需要在脚本销毁时OnDestroy()生命周期中,调用写好的RemoveEventListener函数(unity在重新加载当前场景时时,会调用该生命周期函数);
【解决】MissingReferenceException: The object of type ‘GameObject‘ has been destroyed 观察者模式 监听物体被销毁_第3张图片
该函数如下所示

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

你可能感兴趣的:(unity,观察者模式,unity,游戏引擎)