如何使用协程中的值或如何确定何时完成 [英] How to use a value from a Coroutine or tell when it's done

查看:128
本文介绍了如何使用协程中的值或如何确定何时完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,当使用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.

这篇关于如何使用协程中的值或如何确定何时完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆