简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM