【问题标题】:Returning sprite from coroutine [duplicate]从协程返回精灵[重复]
【发布时间】: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 个精灵。如果失败,为什么不直接返回Spritenull
  • @juharr 是的,这就是我的意思。从我的代码中可以看出,我有一个'yield return sprite;'线。我怎么能把它称为我的第二个函数?
  • yield return null; 可能是一个错误。另外,不要使用非通用的IEnumerator。始终使用IEnumerator<T> 或派生类型,您就会明白@juharr 的意思。
  • 您确实意识到 unity 现在支持 async - await?你好像想要一个异步的方法,用最好的tools available
  • @juharr 迭代器是在 Unity 中实现异步方法的一种方式,直到最近才支持 async-await。这个方法虽然是一团糟。

标签: c# image unity3d ienumerator


【解决方案1】:

您不能从协程返回值。所以你需要使用委托。 我会返回纹理并保留 Sprite 创建。

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
}

整个挑战是了解委托和操作的工作原理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 2020-06-13
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多