报错: The object of type 'Button' has been destroyed but you are still trying to access it

错误日志:MissingReferenceException: The object of type 'Button' 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.
UnityEngine.EventSystems.UIBehaviour.IsActive () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/UIBehaviour.cs:22)
UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:32)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:45)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
UnityEngine.EventSystems.EventSystem:Update()

以button为例子如下:

新建一个TestClick脚本

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class TestClick : MonoBehaviour, IPointerClickHandler {
    public UnityAction OnClick;
    public void OnPointerClick(PointerEventData eventData)
    {
        if(OnClick != null)
        {
            OnClick();
        }
    }
}

再建一个TestPanel1脚本:

using UnityEngine;

/// 
/// MissingReferenceException: The object of type 'Button' has been destroyed but you are still trying to access it.
/// 
/// 报错原因:Button上的脚本TestClick继承有IPointerClickHandler接口, 这个问题不大, 但是这个脚本的排列位置在Button上面就会报错,
/// 
public class TestPanel1 : MonoBehaviour {

    public TestClick ts;
    
	// Use this for initialization
	void Start () {
        ts.OnClick = delegate ()
        {
            GameObject.DestroyImmediate(this.gameObject);
        };


    }
}

然后在场景中加一个panel,panel中放一个button,  panel挂上TestPanel1,  button挂上TestClick,然后把TestClick显示顺序移动到move up 到Button脚本上面, 如下图,运行点击按钮就会报错, 

解决办法:把TestClick放在button脚本下面就可以, 由于习惯问题,一般不会出现这种报错情况

报错: The object of type 'Button' has been destroyed but you are still trying to access it_第1张图片

 

报错: The object of type 'Button' has been destroyed but you are still trying to access it_第2张图片

你可能感兴趣的:(Unity3d笔记)