检查图像是否已下载?

时间:2017-07-21 05:22:30

标签: c# unity3d

我使用unity3d www从Web服务器下载图像并将其存储到本地存储中。我唯一的检查是System.IO.File.Exists()来检查它是否已经下载。我的问题是,当Web服务器中的图像更新或替换为相同的确切文件名时,它不会重新下载。我也尝试了www.responseHeaders,但只有在下载图像后才可用。我知道assetbundle但我不想为一张图片创建assetbundle。

修改

这是我的代码,略有修改。 Fist我连接到webserver以获取所有项目数据,包括图像url作为json类型的数据数组。然后我将循环遍历该阵列,该阵列具有要下载的图像的URL。

void ConnectToWeb()
{
    StartCoroutine(AppManager.Instance.WebRequest("http://www.google.com",
        (AppManager.HttpResponse callback) =>
        {
            if (callback.ResponseCode == 0 || callback.ResponseCode != 200)
            {
                throw new ArgumentException(callback.Error);
            }
            if (callback.Done == true)
            {
                StartCoroutine(LoadData(callback.JsonResponse));
            }
        })
    );
}

private IEnumerator LoadData(JsonData itemData)
{
    for (int i = 0; i < itemData["results"].Count; i++)
    {
        if (!System.IO.File.Exists(itemData["results"][i]["picture_name"].ToString()))
        {
            WWW www = new WWW(itemData["results"][i]["picture_url"].ToString());
        while (!www.isDone)
        {
            Debug.Log("downloaded " + (www.progress * 100).ToString() + "%...");
            yield return null;
        }
        File.WriteAllBytes(imagePath, www.bytes);
    }
}

}

1 个答案:

答案 0 :(得分:0)

使用PlayerPrefs

public static void SetBool(string key, bool state)
{
     PlayerPrefs.SetInt(key, state ? 1 : 0);
}

public static bool GetBool(string key)
{
    int value = PlayerPrefs.GetInt(key);
    return value == 1 ? true : false;
}

void DownloadImage() {
    var isDownloaded = GetBool("IsImageDownloaded"); // <-- Check this first!
    if(!isDownloaded) {
       DownloadImageInternal(); // The real function to download an image
       SetBool("IsImageDownloaded", true);
    }
}

请注意,System.IO.File.Exists()可能适用于桌面,Android和iOS应用程序,也可能不适用于Unity编辑器,但在部署到Android或iOS设备时可能会崩溃。

相关问题