今天為了要暫存檔案所以上網找了一下資源

發現www.texture 要改成使用www.LoadFromCacheOrDownload 是不可能的,因為前者可以直接使用www.texture存取資源,後者只適用於加載 AssetBundle

所以要暫存網路上下載的圖檔必須自已實作,暫存機制

public WWW GetCachedWWW(string url)
{
    string filePath = Application.temporaryCachePath;
    filePath += "/" + url.GetHashCode();
    string loadFilepath = filePath;
    bool web = false;
    WWW www;
    bool useCached = false;
    useCached = System.IO.File.Exists(filePath);
    if (useCached)
    {
        //check how old
        System.DateTime written = File.GetLastWriteTimeUtc(filePath);
        System.DateTime now = ServerTime.Now.DateTime;
        double totalHours = now.Subtract(written).TotalHours;
        if (totalHours > 168)
            useCached = false;
    }

    if (useCached)
    {
        string pathforwww = "file://" + loadFilepath;
        //Debug.Log("TRYING FROM CACHE " + url + "  file " + pathforwww);
        www = new WWW(pathforwww);
    }
    else
    {
        web = true;
        www = new WWW(url);
    }
    StartCoroutine(DoLoad(www, filePath, web, url));
    return www;
}

public static WWW CachePicWWW;
Dictionary<string, Texture> picMap;
IEnumerator DoLoad(WWW www, string filePath, bool web, string fileURL)
{
    yield return www;
    
    if (www.error == null)
    {
        if (web)
        {
            //System.IO.Directory.GetFiles
            //Debug.Log("SAVING DOWNLOAD  " + www.url + " to " + filePath);
            // string fullPath = filePath;
            File.WriteAllBytes(filePath, www.bytes);
            Debug.Log("SAVING DONE  " + www.url + " to " + filePath);
        }
        else
        {
            Debug.Log("SUCCESS CACHE LOAD OF " + www.url);
        }
        picMap[fileURL] = www.texture;
        CachePicWWW = www;

    }
    else
    {

        Debug.Log("WWW ERROR " + www.error);
        if (CachePicWWW != null) {
            picMap[fileURL] = CachePicWWW.texture;
        } else {
            if (!web)
            {
                File.Delete(filePath);
            }
        }

    }
 //do after....
}

將從網路上讀取的圖檔使用HashCode當檔名,下載完成時存入picMap

利用檔案時間來判別是否要重新從網路上下載

因為unity 短時間重覆讀取會出現error問題,所以利用CachePicWWW來解決此問題

 

arrow
arrow
    文章標籤
    unity c# LoadFromCacheOrDownload
    全站熱搜

    狼翔月影 發表在 痞客邦 留言(0) 人氣()