[英]Coroutine wont load new scene after wait for 3 seconds
我得到了這個腳本。 這個想法是在完成游戲后觸發 LoadNextScene()。 這將加載一個名為“做得好”的場景。 該場景應打開大約三秒鍾,然后加載稱為“開始菜單”的場景。
這成功了一半。 當游戲完成時,“做得好”場景被加載,但“開始菜單”沒有加載,並且 MyCoroutine() 中的調試消息沒有打印出來。
有什么問題?
我也在考慮我是否應該像我在代碼中那樣停止我的協程作為良好實踐?
這是我的代碼:
public void LoadNextScene()
{
Debug.Log("NEXT SCENE WAIT 3 sec");
SceneManager.LoadScene("Well done");
Debug.Log("Start waiting");
StartCoroutine(MyCoroutine());
StopCoroutine(MyCoroutine());
}
private IEnumerator MyCoroutine()
{
yield return new WaitForSeconds(3);
Debug.Log("Finish waiting and load start menu");
SceneManager.LoadScene("Start Menu");
}
在你的第一個SceneManager.Load
當前場景這個腳本實例所屬的場景被卸載 → 這個游戲對象被銷毀 → 沒有人再運行你的協程了。
出於某種原因,您在啟動后立即額外使用StopCoroutine
,因此它無論如何都不會運行 → 不,這沒有任何意義;)
或者,您可以簡單地在Well Done
場景中使用單獨的專用腳本,該腳本會在 3 秒后自動返回主菜單。
實際上,為了使其更加靈活和可重用,您可以擁有一個類似的組件
public class SwitchSceneDelayed : MonoBehaviour
{
// Configure these in the Inspector
[SerializeField] bool autoSwitch = true;
[SerializeField] float _delay = 3f;
[SerializeField] string targetScene = "Start menu";
private void Start()
{
if(autoSwitch) StartCoroutine(SwitchDelayedRoutine(_delay));
}
public void SwitchDelayed()
{
StartCoroutine(SwitchDelayedRoutine(targetScene, _delay));
}
public void SwitchDelayed(float delay)
{
StartCoroutine(SwitchDelayedRoutine(targetScene, delay));
}
public void SwitchDelayed(string scene)
{
StartCoroutine(SwitchDelayedRoutine(scene, _delay));
}
public void SwitchDelayed(string scene, float delay)
{
StartCoroutine(SwitchDelayedRoutine(scene, delay));
}
private IEnumerator SwitchDelayedRoutine(string scene, float delay)
{
Debug.Log($"Started waiting for {delay} seconds ...");
yield return new WaitForSeconds (delay);
SceneManager.LoadScene(scene);
}
}
因此,此腳本允許您在delay
秒后切換延遲到targetScene
中配置的另一個場景。 如果啟用autoSwitch
,例程將立即啟動,否則您可以隨時通過調用SwitchDelayed
觸發它。
把它放在你的Well Done
場景中,然后只做
public void LoadNextScene()
{
SceneManager.LoadScene("Well done");
}
在您的原始腳本中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.