Skip to content

Instantly share code, notes, and snippets.

@Guendeli
Last active April 15, 2021 12:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Guendeli/1f5f95c4e2d73fc684b2ad077a09d830 to your computer and use it in GitHub Desktop.
Save Guendeli/1f5f95c4e2d73fc684b2ad077a09d830 to your computer and use it in GitHub Desktop.
Unity offer no method to Load from file or Download besides AssetBundles, here is a class to Cache stuff into the persistent file path, then check if it exists before calling a WWW to download.
using UnityEngine;
using System;
using System.Collections;
using System.IO;
/// <summary>
///
/// </summary>
public class TextureCache
{
string strToBase64(string str)
{
byte[] byt = System.Text.Encoding.UTF8.GetBytes(str);
return Convert.ToBase64String(byt);
}
string base64ToStr(string base64)
{
byte[] b = Convert.FromBase64String(base64);
return System.Text.Encoding.UTF8.GetString(b);
}
string urlToCachePath(string url)
{
return Application.persistentDataPath + "/" + strToBase64(url);
}
public bool HasCache(string url)
{
return File.Exists(urlToCachePath(url));
}
public void WriteCache(WWW www)
{
File.WriteAllBytes(urlToCachePath(www.url), www.bytes);
}
public string CacheUrl(string url)
{
string path = urlToCachePath(url);
if (File.Exists(path))
{
return "file://" + path;
}
Debug.LogWarning("dont have cache url:" + url);
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment