为什么这个协程只运行一次

本文关键字:一次 运行 为什么 | 更新日期: 2023-09-27 18:10:15

"Something"只打印一次…

IEnumerator printSomething;
void Start () {
    printSomething = PrintSomething();
    StartCoroutine (printSomething);
}
IEnumerator PrintSomething () {
    print ("Something");
    yield return null;
    StartCoroutine (printSomething);
}

为什么这个协程只运行一次

方法中的错误在于保存了枚举数。枚举数已经在"枚举",因此两次将枚举数赋给StartCoroutine -方法基本上会导致直接退出协程,因为枚举数之前已经使用过。再次启动协程可以通过再次调用该函数来完成。

StartCoroutine(PrintSomething());

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

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

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

尝试用协例程的名称代替指针。或协同程序本身

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

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

我遇到了这个完全相同的问题,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;
}