目前我有一个具有DontDestroyOnLoad
功能的计时器,以便循环播放需要计时器的场景,我的问题是当游戏加载主菜单场景时如何销毁我的计时器?
答案 0 :(得分: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
答案 1 :(得分:1)
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()
}
}