【问题标题】:Why does this Coroutine only run once?为什么这个协程只运行一次?
【发布时间】:2015-08-29 02:10:22
【问题描述】:

"Something" 只打印一次...

IEnumerator printSomething;

void Start () {

    printSomething = PrintSomething();
    StartCoroutine (printSomething);

}

IEnumerator PrintSomething () {

    print ("Something");

    yield return null;
    StartCoroutine (printSomething);

}

【问题讨论】:

    标签: c# unity3d ienumerator


    【解决方案1】:

    您的方法中的错误是您保存了枚举数。枚举器已经在“枚举”,因此将枚举器提供给StartCoroutine-方法两次基本上会导致协程直接退出,因为之前使用过枚举器。再次调用该函数即可再次启动协程。

    StartCoroutine(PrintSomething());
    

    但与其一遍又一遍地启动协程,不如尝试在内部使用循环。

    while (true)
    {
        print("something");
        yield return null;
    }
    

    这更好,因为协程的内部处理及其开销是未知的。

    【讨论】:

    • 我实际上会更新分配给 printSomething 的内容,它可能是不同的 IEnumerator。
    【解决方案2】:

    尝试使用协程的名称而不是指针。或者协程本身。

    IEnumerator PrintSomething () 
    {
        print ("Something");
    
        yield return null;
    
        StartCoroutine ("PrintSomething");
    }
    

    或者

    IEnumerator PrintSomething () 
    {
        print ("Something");
    
        yield return null;
    
        StartCoroutine (this.PrintSomething());
    }
    

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,Felix K. 是正确的,因为它假定 IEnumerator 已经运行并立即返回。我的解决方案是传递函数本身,以便我们在每次调用它时生成一个新的 IEnumerator。我希望这对其他人有帮助!

      public IEnumerator LoopAction(Func<IEnumerator> stateAction)
      {
          while(true)
          {
              yield return stateAction.Invoke();
          }
      }
      
      public Coroutine PlayAction(Func<IEnumerator> stateAction, bool loop = false)
      {
          Coroutine action;
          if(loop)
          {
              //If want to loop, pass function call
              action = StartCoroutine(LoopAction(stateAction));
          }
          else
          {
              //if want to call normally, get IEnumerator from function
              action = StartCoroutine(stateAction.Invoke());
          }
      
          return action;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-17
        • 1970-01-01
        • 2020-12-27
        • 1970-01-01
        相关资源
        最近更新 更多