如何使协程有序运行? [英] How to make coroutines run in order?

查看:88
本文介绍了如何使协程有序运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这正在使用Unity3D.我有三个协程:GetJSONFromSelectedSubreddit()LoadMoreMemes()和一个单独脚本中的函数,该脚本需要能够通过GetNewMemes()函数访问模因数组(必须返回类型Meme []). LoadNewMemes()产生.问题是,LoadMoreMemes()需要json才能工作,因此它们必须按上述顺序运行.如果需要这些功能,它们是:

This is using Unity3D. I have three coroutines: GetJSONFromSelectedSubreddit(), LoadMoreMemes(), and a function in a separate script that needs to be able to access the array of memes through the GetNewMemes() function (must return type Meme[]). LoadNewMemes() produces. The thing is, LoadMoreMemes() requires the json to work, so they have to run in the mentioned order. If you need the functions, here they are:

public void GetNewMemes(string subReddit, int count)
{
    SetSelectedSubreddit(subReddit);
    memesAtATime = count;
    subJSON = null;
    StartCoroutine(GetJSONFromSelectedSubreddit());
    StartCoroutine(LoadMoreMemes());
}

IEnumerator GetJSONFromSelectedSubreddit()
{
    gettingJSON = true;
    WWW requester = new WWW("https://www.reddit.com/r/" + selectedSub + "/new.json?sort=new&count=25&after=" + postIndex);
    yield return requester;
    subJSON = requester.text;
    json = new JSONObject(subJSON);
    gettingJSON = false;
}

IEnumerator LoadMoreMemes()
{
    while (gettingJSON)
        yield return new WaitForSeconds(0.1f);
    for (int i = 0; i < memesAtATime; i++)
    {
        yield return StartCoroutine(GetUserPostKarma(json["data"]["children"][i]["data"]["author"].str));

        string sourceURL = json["data"]["children"][i]["data"]["preview"]["images"][0]["source"]["url"].str;
        sourceURL = sourceURL.Replace("&amp;", "&");

        yield return StartCoroutine(GrabImage(sourceURL));

        Meme currentMeme = new Meme(
                json["data"]["children"][i]["data"]["preview"]["images"][0]["source"]["url"].str,
                authorPostKarma,
                (int) json["data"]["children"][i]["data"]["score"].i,
                json["data"]["children"][i]["data"]["permalink"].str,
                json["data"]["children"][i]["data"]["title"].str,
                currentBitmap
        );
        Debug.Log(currentMeme.cost);
        memes[i] = currentMeme;
    }
}

这是另一个脚本:

void Start ()
{
    RedditCommunicator redditCommunicator = GetComponent<RedditCommunicator>();
    redditCommunicator.GetNewMemes("me_irl", 1);
    Meme[] memes = redditCommunicator.GetCurrentMemes();
    Debug.Log(memes[0].currentScore);
    redditCommunicator.SpawnOneMeme(memes[0]);
}

每个函数都可以正常运行,但是它们需要彼此等待才能完成,并且需要以正确的顺序运行.我希望这些功能保持独立,以便将来可以单独调用它们. memes是一个私有变量,我想传递给另一个调用这些函数的脚本.如果您认为我没有尝试过我自己的选择,请谷歌搜索并独自解决这个问题,请相信我,我已经尽力了.感谢您的帮助.如果您需要更多信息,请向我询问.该代码的当前状态是,它会在协同程序完成之前将模因返回到较早的状态,从而导致模因为空.

Each function works fine on its own, but they need to wait for each other to finish, as well as run in the correct order to work. I'd like the functions to stay separate so I can call them individually in the future. memes is a private variable, and the one I'd like to pass to the other script calling these functions. If you don't think I've tried my options Googling and solving this on my own, just believe me, I've done my best. Thanks for your help in advance. If you need more information, just ask me for it. The current state of this code is it returns memes to early, before the coroutines can finish, resulting in empty memes.

推荐答案

您可以在IEnumerator中生成一个协程,这将停止该协程的进程,直到完成协程为止.像这样:

You can yield a Coroutine in an IEnumerator which will halt the progression of that Coroutine until that Coroutine is done. Like this:

void Start()
{
    StartCoroutine(DoThings((text) => {
        Debug.Log("Dothings told me: " + text);
    }));
}

IEnumerator DoThings(Action<string>() callback)
{
    yield return StartCoroutine(DoThisFirst());
    callback("Returning a value mid-method!");
    yield return StartCoroutine(ThenThis());
    Debug.Log(3);
}

IEnumerator DoThisFirst()
{
    yield return new WaitForSeconds(1);
    Debug.Log(1);
}

IEnumerator ThenThis()
{
    yield return new WaitForSeconds(1);
    Debug.Log(2);
}

这篇关于如何使协程有序运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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