为什么这个Coroutine只运行一次?

时间:2015-08-29 02:10:22

标签: c# unity3d ienumerator

"东西"只打印一次......

IEnumerator printSomething;

void Start () {

    printSomething = PrintSomething();
    StartCoroutine (printSomething);

}

IEnumerator PrintSomething () {

    print ("Something");

    yield return null;
    StartCoroutine (printSomething);

}

3 个答案:

答案 0 :(得分:2)

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

StartCoroutine(PrintSomething());

但是不要一遍又一遍地启动协程,而是尝试在内部使用循环。

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

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

答案 1 :(得分:1)

尝试使用co-routine的名称而不是指针。或者共同例行公事。

IEnumerator PrintSomething () 
{
    print ("Something");

    yield return null;

    StartCoroutine ("PrintSomething");
}

或者

IEnumerator PrintSomething () 
{
    print ("Something");

    yield return null;

    StartCoroutine (this.PrintSomething());
}

答案 2 :(得分:1)

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