【发布时间】:2016-07-23 17:12:38
【问题描述】:
我有一个团结的场景。它使用 http 请求获取图像并每两秒显示一次。这些图像的顺序很重要。所以,程序的步骤:
- 使用http请求获取图片
- 显示它,更新索引计数器
- 转到步骤 1
我的代码在这里:
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 个文件。Unity documentation 说
这将等待协程完成执行。
所以我希望我的代码应该能成功运行,但不会。
编辑
我将一个变量定义为一个标志。我初始化并控制它等待。这个对我有用。
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;
}
}
【问题讨论】:
-
你说你期望 19 个 png 文件,所以这意味着你需要获取图像并每 2 秒显示 19 次?这些图片是来自同一链接还是您下载了 19 次同一图片?你想做什么?
-
这是我这辈子见过的最奇怪的代码
-
重要提示您绝对必须使用 Application.persistentDataPath。这对于 Unity 来说是一件非常令人困惑的事情。 (1)你必须 - 总是 - 到处 - 只 - 使用 Application.persistentDataPath 不过(2)Unity在文档中提到了其他路径。但是 (3) 参见第 1 点。
-
@Programmer url字符串的内容每次都不一样。它有 19 种不同的查询。我没有写文案,因为这部分暂时不重要,我
-
请参阅"Should questions include “tags” in their titles?",其中的共识是“不,他们不应该”!
标签: unity3d httprequest coroutine yield-return