问题
I currently have 2 functions.
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;
}
}
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.
回答1:
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;)
}
}
Then you call:
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.
来源:https://stackoverflow.com/questions/47805381/returning-sprite-from-coroutine