簡體   English   中英

為什么這個協程只運行一次?

[英]Why does this Coroutine only run once?

“某事”只打印一次......

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM