如何使用协程中的值或如何确定何时完成

问题描述:

例如,当使用WWW类调用Web API时,我希望返回一个值或有关完成时间及其状态的一些反馈.

For instance, when calling a web API with the WWW-class, I'd like a value returned or some feedback on when it's done and its status.

那么,让我向我展示一种简洁的方法!

Well then, me, let me show me a neat way of doing this!

在这里,我们制作一个IEnumerator,它以Action(在我们的情况下为方法)作为参数,并在完成WWW时调用它:

Here we make an IEnumerator that takes in an Action (method in our case) as parameter and call it when our WWW is done:

    public static IEnumerator GetSomething(Action<string> callback)
    {
        // The www-stuff isn't really important to what I wish to mediate
        WWWForm wwwForm = new WWWForm();
        wwwForm.AddField("select", "something");
        WWW www = new WWW(URL, wwwForm);
        yield return www;

        if (www.error == null)
        {
            callback(www.text);
        }
        else
        {
            callback("Error");
        }
    }

这就是我们的用法:

StartCoroutine(
    GetSomething((text) => 
    {
        if (text != "Error")
        {
            // Do something with the text you got from the WWW
        }
        else
        {
            // Handle the error
        }
    })
);

我们发送的参数是(text),这是一个无名声明的方法.我们在IEnumerator中将其称为回调",但可以将其称为任何东西,重要的是它调用在调用方法GetSomething的参数中声明的方法.

The parameter we send in is (text) which is a namelessly declared method. We call it "callback" in the IEnumerator but it can be called anything, what's important is that it calls the method we have declared in the parameters of where we call the method GetSomething.