代码之家  ›  专栏  ›  技术社区  ›  innomotion media

统一:从定时器触发时LoadScene不工作

  •  0
  • innomotion media  · 技术社区  · 6 年前

    在我的游戏中,当玩家死亡时,会播放死亡的声音,一旦声音结束,当用户还有足够的生命时,应该重新加载场景。

    在我听到声音之前,在调用death()函数时,游戏立即停止了:

    public static void Death()
    {
        AddCoinScript.coinCounter = 0;
        LivesScript.livesCounter--;
    
            if (LivesScript.livesCounter > -1)//to get 0 live
            {
                Debug.Log("TIMER");
    
                var currentScene = SceneManager.GetActiveScene();
                SceneManager.LoadScene(currentScene.name);
            }
            else
            {
                //TO DO GameOver
            }
    
    }
    

    这很管用。

    public static void Death()
    {
        AddCoinScript.coinCounter = 0;
        LivesScript.livesCounter--;
    
        PlayDeathSound();
    
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = aSDeath.clip.length * 1000;
        timer.Start();
    
        timer.Elapsed += delegate
        {
            timer.Stop();
    
            if (LivesScript.livesCounter > -1)//to get 0 live
            {
                Debug.Log("TIMER");
    
                var currentScene = SceneManager.GetActiveScene();
                SceneManager.LoadScene(currentScene.name);
            }
            else
            {
                //TO DO GameOver
            }
        };
    }
    

    如你所见,为了确保计时器真正启动,我设置了一个“调试日志(“定时器”)“看看,如果它真的工作。你猜怎么着:是的。调试现在在控制台中显示“TIMER”。但你知道什么不再管用了吗?下面的两行代码。

                var currentScene = SceneManager.GetActiveScene();
                SceneManager.LoadScene(currentScene.name);
    

    当我把它全部改回来时,它又起作用了。只有当计时器触发这两行时,它们才会被忽略。

    这太奇怪了还是我遗漏了什么?谢谢您!

    0 回复  |  直到 6 年前
        1
  •  3
  •   Ali Kanat    6 年前

    好吧,我不是C#和委托方面的专家,但显然它创建了一个单独的线程,您只能使用 SceneManager.GetActiveScene

    delegate

    public void Death()
    {
        StartCoroutine(DeathCoroutine());
    }
    IEnumerator DeathCoroutine()
    {      
    
        AddCoinScript.coinCounter = 0;
        LivesScript.livesCounter--;
        PlayDeathSound();
        // wait for duration of the clip than continue executing rest of the code
        yield return new WaitForSeconds(aSDeath.clip.length);
    
        if (LivesScript.livesCounter > -1)//to get 0 live
        {
            Debug.Log("TIMER");
    
             var currentScene = SceneManager.GetActiveScene();
             SceneManager.LoadScene(currentScene.name);
        }
        else
        {
             //TO DO GameOver
        }
    
    }
    
        2
  •  1
  •   Jichael    6 年前

    使用协同程序怎么样?你只要在玩家死的时候启动它,在你的声音还在播放的时候屈服。