简体   繁体   English

unity C#:加载新场景时销毁object

[英]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?目前我有一个计时器,它有DontDestroyOnLoad function 以便它在需要计时器的场景中循环,我的问题是当游戏加载主菜单场景时如何销毁我的计时器?

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 由于DontDestroyOnLoad而已在场景中的计时器将不会调用Start函数(因为在脚本的生命周期中仅调用了一次),因此不会将其销毁

You have two options. 您有两个选择。

You can call Destroy(gameObject); 您可以调用Destroy(gameObject); or DestroyImmediate() in your timer script. 或您的计时器脚本中的DestroyImmediate() It will Destroy that timer script and GameObject. 它将销毁该计时器脚本和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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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