重新加载场景后,为什么我的非静态GameObject在脚本中会丢失其引用?

问题描述

我的Canvas上有一个空的GameObject,用于显示广告菜单,我通过检查器将其附加到公共变量中的单独脚本(不在菜单本身上)。

我正在使用adMenu.SetActive(false)的脚本中将其设置为非活动状态,该脚本可用于游戏的第一个播放过程。但是,当我通过场景中的按钮重新启动场景时,菜单失去了对检查器中相同GameObject的引用,并且我收到此错误

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.

在重新加载场景之后,以其他类似方式初始化其他游戏对象时,这从未发生过。

其他详细信息:

  • GameObject.Find()可以从同一脚本中使用其名称检索GameObject
  • DontDestroyOnLoad()不在脚本上或其所附的GameObject上的任何地方使用

代码

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Advertisements;
using MEC;

public class AdManager : MonoBehavIoUr,IUnityAdsListener
{
    internal static AdManager instance;
    private static bool isInitialized = false;

    public GameObject adMenu;
    private string placement = "rewardedVideo";

    void Start()
    {
        instance = this;
        if (!isInitialized)
        {
            isInitialized = true;
            Advertisement.AddListener(this);
            Advertisement.Initialize(Constants.appleGameId,true);
        }
    }

    IEnumerator<float> ShowAd()
    {
        if (!Advertisement.IsReady())
        {
            yield return Timing.WaitForOneFrame;
        }
        Advertisement.Show(placement);
    }

    public void CloseAdMenu()
    {
        Debug.Log("Is adMenu null: " + (adMenu == null));  // Returns false on first playthrough only
        adMenu.SetActive(false);
    }


    public void OnUnityAdsDidFinish(string placementId,ShowResult showResult)
    {
        if (showResult == ShowResult.Finished)
        {
            CloseAdMenu();
        }
    }

    public void OnUnityAdsReady(string placementId)
    {
        // throw new System.NotImplementedException();
    }

    public void OnUnityAdsDidError(string message)
    {
        // throw new System.NotImplementedException();
    }

    public void OnUnityAdsDidStart(string placementId)
    {
        // throw new System.NotImplementedException();
    }
}

解决方法

发生的情况与您的菜单对象或static实例无关。

问题是回调

public void OnUnityAdsDidFinish(string placementId,ShowResult showResult)

因为您通过

注册了实例
Advertisement.AddListener(this);

但场景更改后,this实例将成为毁灭者。

the examples所示,您应该这样做

private void OnDestroy() 
{
    Advertisement.RemoveListener(this);
}
,

在重新启动方法上,应使用adMenu.SetActive(true)重新激活按钮,如果没有,则在再次调用场景时,adMenu GameObject被禁用,因此您不能访问GameObject

也许您可以在AdManager中添加以下方法:

public void OpenAdMenu()
{
    adMenu.SetActive(true);
}

并在AdManager.Start()

上调用