从协程返回精灵 [英] Returning sprite from coroutine
问题描述
我目前有2个功能.
我的第一个是IEnumerator
,我们叫它LoadImage
,它负责从URL下载图像.
My first one is an IEnumerator
, let's call it LoadImage
, it handles downloading the image from a 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()
函数分配我的精灵的建议.
My second function needs to assign that LoadImage()
's output (which is a sprite) to my GameObject
. I cant just put my GameObject
and load it in the LoadImage()
function. If possible, I need advice on how I can assign my the sprite from the LoadImage()
function.
推荐答案
您不能从协程返回值.因此,您需要使用委托. 我将返回Texture,将Sprite的创建省去.
You can't return a value from coroutine. So you need to use delegate. I would return the Texture and leave the Sprite creation out.
IEnumerator LoadImage(Action<Texture2D> callback)
{
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");
callback(null);
}
else
{
Debug.Log("Download succes");
Texture2D texture = new Texture2D(1, 1);
www.LoadImageIntoTexture(texture);
callback(texture;)
}
}
然后您致电:
void Start()
{
StartCoroutine(LoadImage(CreateSpriteFromTexture));
}
private CreateSpriteFromTexture(Texture2D texture)
{
if(texture == null) { return;}
Sprite sprite = Sprite.Create(texture,
new Rect(0, 0, texture.width, texture.height), Vector2.zero);
// Assign sprite to image
}
整个挑战是了解委派和行动的工作方式.
The whole challenge is to understand how delegate and action work.
这篇关于从协程返回精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!