Reputation: 79
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.
Upvotes: 0
Views: 1614
Reputation: 717
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.
Upvotes: 1