'Unity C# : Destroy object when a new scene loads

currently I have a timer that has DontDestroyOnLoad function in order for it to cycle through scenes that needed a timer, my question is how can I destroy my timer when the game loads the main menu scene?



Solution 1:[1]

In the Start function of the Timer, find the objects holding the script and check if there are more than two of these objects :

private void Start()
{
      Timer[] timers = FindObjectsOfType(typeof(Timer)) as Timer[];
      if( timers.Length > 1 )
         Destroy( gameObject ) ;
}

The timer already in the scene because of the DontDestroyOnLoad won't call the Start function (since it is called only once in the life cycle of the script), thus, it won't be destroyed

Solution 2:[2]

You have two options.

You can call Destroy(gameObject); or DestroyImmediate() in your timer script. It will Destroy that timer script and GameObject.

Another option is to have a function that will stop the timer then reset timer variables to its default value. This is good in terms of memory management on mobile devices.

public class Timer: MonoBehaviour
{
    public void StopAndResetTimer()
    {
        //Stop Timer

        //Reset Timer variables
    }

    public void DestroyTimer()
    {
        Destroy(gameObject);
        // DestroyImmediate(gameObject);
    }
}

Then in your Main Menu script

public class MainMenu: MonoBehaviour
{

    Timer timerScript;
    void Start()
    {
        timerScript = GameObject.Find("GameObjectTimerIsAttachedTo").GetComponent<Timer>();
        timerScript.DestroyTimer();

        //Or option 2
        timerScript.StopAndResetTimer()
    }
}

Solution 3:[3]

This may solve your problem:

private void Start()
{
    if (SceneManager.GetActiveScene().name == "main menu") // check if current scene in main menu, (be sure the name match with your scene)
    {
        var timer = GameObject.FindObjectOfType<Timer>(); // find your timer component

        if (timer) Destroy(timer.gameObject); // destroy that
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hellium
Solution 2 Programmer
Solution 3 KiynL