Coroutine第二次不工作

时间:2016-10-07 12:38:55

标签: c# unity3d

在我的游戏中,我有主菜单,通过它我开始新游戏(加载另一个场景)并执行下面的脚本。但是当我回到主菜单并再次开始新游戏时,下面的脚本不起作用。我试图在Start函数中停止协同程序,但它没有帮助

private IEnumerator OpenCloseEyesAnimation()
 {
     if (!isOpenEyesAnimationStarted)
     {
         isOpenEyesAnimationStarted = true;
         openCloseEyes.OpenCloseDoor(); // this work 1st and 2nd time
         yield return new WaitForSeconds(6.0f); // this line don't work 2nd time
         stepNumber++;
         isOpenEyesAnimationStarted = false;
     }
 }

我在Update函数中调用它一次

enter image description here

1 个答案:

答案 0 :(得分:3)

您应该在适当的位置使用StopCoroutine。每次启动Coroutine时,请先停止它。

 private IEnumerator OpenCloseEyesAnimation()
     {
         if (!isOpenEyesAnimationStarted)
         {

             isOpenEyesAnimationStarted = true;
             openCloseEyes.OpenCloseDoor();
             yield return new WaitForSeconds(6.0f); // this line don't work after second launch
             stepNumber++;
             isOpenEyesAnimationStarted = false;
         }
     }

正如Commment提到的那样(@Paradox Forge)更新你的UpdateEvent代码:

case 3: 
  StopCoroutine(OpenCloseEyesAnimation());
  isOpenEyesAnimationStarted = false;
  StartCoroutine(OpenCloseEyesAnimation());