0
votes

I want to add admob into my game and don't want to request/load the ad everytime I change the scenes. I tried to solve that with "DontDestroyOnLoad", but somehow the object where my AdManager script is attached to, will be destroyed, when I change between other scenes.

This is the code, I wrote into my AdManager script.

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

The AdManager script is getting called in the main menu (when I start the game). When I press the "Start"-Button, the AdManager script should be available in the other scenes, but it just disappears/gets destroyed.

1
Instead of using DontDestroyOnLoad, I recommend using SceneManager instead. The idea is you make a scene that contains the objects you want to maintain across multiple other scenes, and then use SceneManager to load and unload those other scenes on top of your scene with the objects that should never be destroyed. Video tutorial.Tim Hunter

1 Answers

1
votes

You should have a variable for Its own reference as well.

 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);
 }

Let me know if it helps.