在 Unity Coroutine 中等待事件?

The*_*ler 2 c# coroutine unity-game-engine

所以我有一个 Unity 协程方法,其中我有一些对象。这些对象代表从某处服务器收集的值,Updated它们在准备好时发送一个事件。

我想知道在 Unity 的协程中等待所有值更新的最佳方法是什么。

public IEnumerator DoStuff()
{
    foreach(var val in _updateableValues)
    {
        if (val.Value != null) continue;
        else **wait for val.Updated to be fired then continue**
    }
    //... here I do stuff with all the values
    // I use the WWW class here, so that's why it's a coroutine
}
Run Code Online (Sandbox Code Playgroud)

做这样的事情的最佳方法是什么?

谢谢!

Xen*_*oRo 6

没有内置的直接方法来等待事件本身,但您可以使用同步嵌套协程来等待事件设置的标志:

//Flag
bool eventHappened;

//Event subscriber that sets the flag
void OnEvent(){
    eventHappened=true;
}

//Coroutine that waits until the flag is set
IEnumerator WaitForEvent() {
    yield return new WaitUntil(eventHappened);
    eventHappened=false;
}

//Main coroutine, that stops and waits somewhere within it's execution
IEnumerator MainCoroutine(){
   //Other stuff...
   yield return StartCoroutine(WaitForEvent());
   //Oher stuff...
}
Run Code Online (Sandbox Code Playgroud)

考虑到这一点,创建一个等待 an 的通用协程UnityEvent很容易:

private IEnumerator WaitUntilEvent(UnityEvent unityEvent) {
    var trigger = false;
    Action action = () => trigger = true;
    unityEvent.AddListener(action.Invoke);
    yield return new WaitUntil(()=>trigger);
    unityEvent.RemoveListener(action.Invoke);
}
Run Code Online (Sandbox Code Playgroud)