【问题标题】:DontDestroyOnLoad is destroying object when changing scenesDontDestroyOnLoad 在改变场景时正在销毁对象
【发布时间】:2019-05-04 12:28:12
【问题描述】:

我想将 admob 添加到我的游戏中,并且不想在每次更改场景时都请求/加载广告。 我试图用“DontDestroyOnLoad”解决这个问题,但是当我在其他场景之间切换时,我的 AdManager 脚本所附加到的对象会以某种方式被破坏。

这是我在 AdManager 脚本中写入的代码。

private static bool created = false;
...
void Awake()
{
    if (!created)
    {
        DontDestroyOnLoad(gameObject);
        created = true;
    }
    else
    {
        Destroy(gameObject);
    }
}

AdManager 脚本在主菜单中被调用(当我开始游戏时)。当我按下“开始”按钮时,AdManager 脚本应该在其他场景中可用,但它只是消失/被破坏。

【问题讨论】:

  • 我建议不要使用 DontDestroyOnLoad,而是使用 SceneManager。这个想法是您制作一个包含要在多个其他场景中维护的对象的场景,然后使用 SceneManager 在场景顶部加载和卸载那些不应该被破坏的对象的其他场景。 Video tutorial.

标签: c# unity3d admob game-development


【解决方案1】:

你也应该有一个变量供它自己参考。

 private static [YourScriptName] _instance = null;
 public static [YourScriptName] Instance
 {
     get { return _instance; }
 }


 void Awake()
 {
     if (_instance != null && _instance != this)
     {
         Destroy(gameObject);
         return;
     }

     _instance = this;

     DontDestroyOnLoad(gameObject);
 }

如果有帮助,请告诉我。

【讨论】:

  • 如果你想在 DontDestroyOnLoad 上有一个游戏对象,你应该在整个游戏中只有一个游戏对象。最好在主菜单或飞溅场景中。您是否检查过您的游戏场景是否也有预制件?
  • 是的,我到处都删除了带有“AdManager”脚本的 GameObject。它仅在主菜单场景中。它仍然无法正常工作。当我在场景之间切换时,应该在层次结构中看到带有“AdManager”脚本的游戏对象,对吧?
  • 请发布完整的脚本。将尝试对其进行测试。
  • 脚本太长。我会尝试以某种方式解决这个问题,或者其他人可能知道这个问题。不过,谢谢!
  • 已修复。问题是。带有 DontDestroyOnLoad 的游戏对象是另一个游戏对象的子对象。
猜你喜欢
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
  • 1970-01-01
相关资源
最近更新 更多