How to use a value from a Coroutine or tell when i

2019-03-04 02:36发布

This question already has an answer here:

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.

标签: unity3d
1条回答
该账号已被封号
2楼-- · 2019-03-04 02:58

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

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

And this is how we use it:

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

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.

查看更多
登录 后发表回答