Mike Apostol
Mike Apostol

Reputation: 39

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?

Upvotes: 1

Views: 2103

Answers (3)

KiynL
KiynL

Reputation: 4266

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

Upvotes: 0

Programmer
Programmer

Reputation: 125275

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

Upvotes: 1

Hellium
Hellium

Reputation: 7346

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

Upvotes: 1

Related Questions