Unity在场景异步中加载www图像

时间:2018-08-22 08:33:43

标签: c# image unity3d asynchronous scene

在Unity中,我有一个主屏幕。当我单击它时,我想打开一个包含微型游戏(900x900)游戏列表的场景。

我的问题是Unity不会在“ loadasync”部分中加载图像。这是我的代码:

Home的代码以异步加载下一个场景(在OnPointerClick中调用)

IEnumerator LoadSceneAsyncIEnumerator(string sceneName)
{
    yield return null;
    AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);
    while (!asyncLoad.isDone)
    {
        yield return null;
    }
}

这是我的ListGames场景的醒来:

void Awake(){
    List<JeuIO> jeux = GetGames ();
    foreach (JeuIO j in jeux){
        StartCoroutine(LoadImageAsync(j.image1));
    }
}

GetGames进行http调用以获取游戏列表(在场景打开之前完成),但是在asyncLoad.isDone == true之前,LoadImageAsync无法解析。

IEnumerator LoadImageAsync(string url) {
    string u = url;
    bool found = false;
    if (File.Exists(Application.persistentDataPath + "/"+url.GetHashCode()+".png")){
        u = Application.persistentDataPath + "/"+url.GetHashCode()+".png";
        found = true;
    }

    WWW www = new WWW(u);
    yield return www;

    Texture2D t = null;
    if(!found && www.bytes != null) {
        File.WriteAllBytes(Application.persistentDataPath + "/"+url.GetHashCode()+".png", www.bytes);
        t = www.textureNonReadable;
    } else {
        t = www.texture;
    }
    if (t != null){
        Sprite.Create(t, new Rect(0, 0, t.width, t.height), new Vector2(0, 0));
    }
    Debug.Log("IMAGE "+url+" OVERRRRRRRR");
}

当然,这不是最终的代码^^我将直接在网格的游戏对象中创建精灵。

那么,在说完等待之前,我怎么能强迫团结创造我所有的精灵?

1 个答案:

答案 0 :(得分:1)

在我看来,您的loadcene脚本和ListGames脚本没有以任何方式连接。因此,目前没有办法强制这种行为。

有多种方法可以解决您的问题。 一个解决方案可能是:

List<JeuIO> jeux移动到ScriptableObject,可以选择将其作为参数传递给LoadScene脚本。这样,您就可以保持某种形式的代码灵活性和可扩展性。

第二,您可能想在LoadImageAsync方法中实现回调函数:

IEnumerator LoadImageAsync(string url, Action<Sprite> callback) {
    // your code
    var sprite Sprite.Create(t, new Rect(0, 0, t.width, t.height), new Vector2(0, 0));


    callback?.Invoke(sprite);
}

像这样实现它:

IEnumerator LoadSceneAsyncIEnumerator(string sceneName, SomeScriptableObject scriptable)
{
    yield return null;
    var targetCount = scriptable.jeux.Count();
    var loadedCount = 0;

    AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);
    foreach (var j in scriptable.jeux)
    {
        // for each image that is processed, increment the counter
        StartCoroutine(LoadImageAsync(j.image1,(sprite) =>
        {
            someList.Add(sprite);
            loadedCount++;
        }));
    }

    while (!asyncLoad.isDone || targetCount != loadedCount)
    {
        yield return null;
    }
}

编辑: 您可以通过将参数传递给Action来检索精灵。 可以在回调中使用。

相关问题