【发布时间】:2018-05-16 04:52:22
【问题描述】:
我有一个场景,我展示了从服务器下载的多个图像。它工作正常,但每次我进入场景时图像都会以不同的顺序显示,我希望始终以相同的顺序出现。有人可以帮帮我吗?
这是代码:
public GameObject contentRef;
public RawImage imgPrefab;
void Start()
{
DownloadtheFiles();
}
public void DownloadtheFiles()
{
List<string> photolist = ES2.LoadList<string>("myPhotos.txt");
for (int i = 0; i < photolist.Count; i++)
{
//Don't capture i variable
int index = i;
new GetUploadedRequest()
.SetUploadId(photolist[index])
.Send((response) =>
{
StartCoroutine(DownloadImages(response.Url, index));
});
}
}
public IEnumerator DownloadImages(string downloadUrl, int index)
{
var www = new WWW(downloadUrl);
yield return www;
//Instantiate the image prefab GameObject and make it a child of the contentRef
RawImage newImg = Instantiate(imgPrefab, contentRef.transform);
//Change the name
newImg.name = "Image-" + index;
//Get the downloaded image
Texture2D tex = new Texture2D(4, 4);
www.LoadImageIntoTexture(tex);
//Apply the downloaded image
newImg.texture = tex;
}
这些是我两次进入场景时不同图像位置的截图:
【问题讨论】:
-
协程是 Unity 特定的多任务处理方式。一旦你开始了多个任务,它们完成的顺序就不再是确定的了。您也许可以制作一个单独的 CoRoutine,以给定的顺序完成所有下载和显示。但是这样做可能不利于网络性能(许多小文件可以从并行下载大量文件中受益)。