首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用包含http请求的协同服务?

如何使用包含http请求的协同服务?
EN

Stack Overflow用户
提问于 2016-04-04 08:38:16
回答 1查看 415关注 0票数 0

我有一个团结的场景。它使用http请求获取图像,并每两秒钟显示一次。这些图像的顺序很重要。因此,程序的步骤:

  1. 使用http请求获取图像
  2. 显示它,更新索引计数器
  3. 转到步骤1

我的密码在这里:

代码语言:javascript
复制
  int counter = 0;
  float tempTimeLimit = 0;

    void Update()
    {
        if (tempTimeLimit > 1)
        {
            // Decrease timeLimit.
            tempTimeLimit -= Time.deltaTime;
        }
        else
        {
            StartCoroutine(_Refresh());
            tempTimeLimit = timeLimit;
        }    
    }

    IEnumerator _Refresh ()
    {
        if (counter < 19)
        {
            counter += 1;
            ......    
            var req = new WWW(url);

            yield return req;

            byte[] data = req.texture.EncodeToPNG();
            File.WriteAllBytes(Application.dataPath + "/../" + counter + ".png", data);

            GetComponent<Renderer>().material.mainTexture = req.texture;

        }
    }

我希望我能看到19个png文件。但我只看到8-9-10个文件。统一文献

这将等到协同线完成执行。

因此,我希望我的代码能够成功地工作,但不会成功。

编辑

我将变量定义为标志。我为等待而贬低和控制它。对我来说很管用。

代码语言:javascript
复制
void Update()
{
        if (!wait)
        {
            wait = true;
            StartCoroutine(_Refresh());
            counter ++;
        }
}
IEnumerator _Refresh ()
{
    if (counter < 19)
    {
        ..........
        var req = new WWW(url + "?" + qs);
        yield return req;
        if (req != null)
           wait = false;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2016-04-04 09:12:14

从几个角度来看,这是错误的,但最重要的是,您没有保证获取图像将在给定的时间内完成。试着做这样的事情:

代码语言:javascript
复制
    void Start()
    {
        StartCoroutine(_Refresh());
    }

    IEnumerator _Refresh ()
    {
        counter = 0;
        while (counter < 19)
        {
            counter += 1;
            ......    
            var req = new WWW(url);

            yield return req;

            byte[] data = req.texture.EncodeToPNG();
            File.WriteAllBytes(Application.dataPath + "/../" + counter + ".png", data);

            GetComponent<Renderer>().material.mainTexture = req.texture;

        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36397951

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档