- Home /
how to keep the script working after scene load?
Okay so, I have a button
public void ShowAd()
{
if (!UnityEngine.Advertisements.Advertisement.IsReady())
{
return;
}
if (m_LatestDisplayedAdTime == -1f
|| Time.time - m_LatestDisplayedAdTime >= m_IntervalBetweenAdsInSecondes)
{
UnityEngine.Advertisements.Advertisement.Show();
m_LatestDisplayedAdTime = Time.time;
PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins", 0) + 500);
}
and i have a timer for 300 seconds . It works fine if i stay in the menu , but if i change scene and get back in the menu i can click it again, even if there is still plenty of time left .. ?? how to keep the script working after scene load ?
Answer by EpiFouloux · Jun 13, 2016 at 07:34 AM
From https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void Awake() {
DontDestroyOnLoad(transform.gameObject);
}
}
"Makes the object target not be destroyed automatically when loading a new scene.
When loading a new level all objects in the scene are destroyed, then the objects in the new level are loaded. In order to preserve an object during level loading call DontDestroyOnLoad on it. If the object is a component or game object then its entire transform hierarchy will not be destroyed either."