Unity3D-下载资源至本地缓存

本文介绍了一个基于Unity的游戏资源缓存管理系统实现。该系统利用BestHTTP插件进行资源下载,并根据不同平台配置缓存路径。文章提供了核心代码示例,包括MD5哈希计算、文件存在检查及创建等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本示例使用BestHTTP插件请求url地址下载至本地,并做缓存管理,易于扩展

using System;
using UnityEngine;
using BestHTTP;
using System.IO;
using System.Security.Cryptography;

public class DownloadCachesMgr : Singleton<DownloadCachesMgr>
{

    public string AssetCachesDir
    {
        get
        {
            string dir = "";
#if UNITY_EDITOR
            dir = Application.dataPath + "Caches/";//路径:/AssetsCaches/
#elif UNITY_IOS
            dir = Application.temporaryCachePath + "/Download/";//路径:Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/Library/Caches/
#elif UNITY_ANDROID
            dir = Application.persistentDataPath + "/Download/";//路径:/data/data/xxx.xxx.xxx/files/
#else
            dir = Application.streamingAssetsPath + "/Download/";//路径:/xxx_Data/StreamingAssets/
#endif
            return dir;
        }
    }

    public string ImagePathName { get { return AssetCachesDir + "Image/"; } }
    public string TextPathName { get { return AssetCachesDir + "Config/"; } }

    private string GetFileName(string url)
    {
        string name = StrToMD5(url);
        return name;
    }

    public static string StrToMD5(string str)
    {
        byte[] data = System.Text.Encoding.GetEncoding("GB2312").GetBytes(str);
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] OutBytes = md5.ComputeHash(data);

        string OutString = "";
        for (int i = 0; i < OutBytes.Length; i++)
        {
            OutString += OutBytes[i].ToString("x2");
        }
        // return OutString.ToUpper();
        return OutString.ToLower();
    }

    private bool CheckFileExists(string path , string name)
    {
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        FileInfo t = new FileInfo(path + "//" + name);
        if (!t.Exists)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    private void CreateFile(string path, string name,byte[] bytes)
    {
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        FileStream fs;
        FileInfo t = new FileInfo(path + "//" + name);
        if (!t.Exists)
        {
            fs = t.Create();
        }
        else
        {
            t.Delete();
            fs = t.Create();
        }
        fs.Write(bytes, 0, bytes.Length);
        fs.Close();
        fs.Dispose();
    }

    public void LoadImage(string url, Action<int, Texture2D> callBack)
    {
        string name = GetFileName(url);
        if (CheckFileExists(ImagePathName,name))
        {
            var bytes = File.ReadAllBytes(ImagePathName + "//" + name);
            Texture2D tex = new Texture2D(0,0);
            tex.LoadImage(bytes);
            callBack(0, tex);
        }
        else
        {
            new HTTPRequest(new Uri(url), (request, response) =>
            {
                if (request.State == HTTPRequestStates.Finished)
                {
                    int result = 0;
                    Texture2D tex = null;
                    if (response.IsSuccess)
                    {
                        byte[] bytes = response.Data;
                        CreateFile(ImagePathName, name, bytes);
                        tex = new Texture2D(0,0);
                        tex.LoadImage(bytes);
                        callBack(result, tex);
                    }
                    else
                    {
                        result = response.StatusCode;
                    }
                    if (callBack != null)
                    {
                        callBack(result, tex);
                    }
                }
            }).Send();
        }
    }

}