【发布时间】:2018-05-28 01:44:11
【问题描述】:
我目前有 2 个函数。
我的第一个是IEnumerator,我们称它为LoadImage,它负责从 URL 下载图像。
IEnumerator LoadImage()
{
WWW www = new WWW("https://s3-ap-northeast-1.amazonaws.com/myeyehouse/uimg/scimg/sc661120171130095837184/pano/thumb_Eyehouse.jpg");
while (!www.isDone)
{
Debug.Log("Download image on progress" + www.progress);
yield return null;
}
if (!string.IsNullOrEmpty(www.error))
{
Debug.Log("Download failed");
}
else
{
Debug.Log("Download succes");
Texture2D texture = new Texture2D(1, 1);
www.LoadImageIntoTexture(texture);
Sprite sprite = Sprite.Create(texture,
new Rect(0, 0, texture.width, texture.height), Vector2.zero);
return sprite;
}
}
我的第二个函数需要将LoadImage() 的输出(它是一个精灵)分配给我的GameObject。我不能只是把我的GameObject 加载到LoadImage() 函数中。如果可能的话,我需要关于如何从 LoadImage() 函数分配我的精灵的建议。
【问题讨论】:
-
为什么要返回 IEnumerator?这将为您提供一组 0 个或多个空值,然后是 0 个或 1 个精灵。如果失败,为什么不直接返回
Sprite或null? -
@juharr 是的,这就是我的意思。从我的代码中可以看出,我有一个'yield return sprite;'线。我怎么能把它称为我的第二个函数?
-
yield return null;可能是一个错误。另外,不要使用非通用的IEnumerator。始终使用IEnumerator<T>或派生类型,您就会明白@juharr 的意思。 -
您确实意识到 unity 现在支持
async-await?你好像想要一个异步的方法,用最好的tools available。 -
@juharr 迭代器是在 Unity 中实现异步方法的一种方式,直到最近才支持
async-await。这个方法虽然是一团糟。
标签: c# image unity3d ienumerator