Unity AssetBundle打包之存储Hash

具体代码如下 注释代码中都有自行查看

using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class BuildEditor : EditorWindow
{
#if UNITY_ANDROID
    static string m_CurPlatformName = "Android";
#elif UNITY_IOS
    static string m_CurPlatformName = "IOS";
#else
    static string m_CurPlatformName = "Windows";
#endif
    /// <summary>
    /// 资源打包路径
    /// </summary>
    private static string m_OutPath = Application.dataPath + "/GameRes";
    /// <summary>
    /// 当前选择的平台
    /// </summary>
    private static BuildTarget m_BuildTarget = EditorUserBuildSettings.activeBuildTarget;
    /// <summary>
    /// 资源输出路径
    /// </summary>
    private static string m_BundlePutPath = Application.streamingAssetsPath + "/" + m_CurPlatformName + "/AssetBundles";
    /// <summary>
    /// 打包列表
    /// </summary>
    private static List<string> finalFiles = new List<string>();
    /// <summary>
    /// 打包完成之后生成的Manifest文件
    /// </summary>
    private static AssetBundleManifest m_Manifest;
    /// <summary>
    /// 打包
    /// </summary>
    [MenuItem("Build/Build ab")]
    private static void Build()
    {
        finalFiles.Clear();
        //1.清除AssetBundleName
        ClearAssetBundleName();
        //2.设置AssetBundleName
        Pack(m_OutPath);
        //3.打包
        if (Directory.Exists(m_BundlePutPath)) Directory.Delete(m_BundlePutPath, true);
        string tempFilePath = m_BundlePutPath;
        Directory.CreateDirectory(m_BundlePutPath);
        m_Manifest = BuildPipeline.BuildAssetBundles(m_BundlePutPath, BuildAssetBundleOptions.DeterministicAssetBundle, m_BuildTarget);
        if (m_Manifest != null)
        {
            DeleteManifestFile(m_BundlePutPath);
            CreateFileList();
            Util.BuildSuccessOrFail("Build AB", "Build Succeed", "OK");
        }
        else
        {
            Util.BuildSuccessOrFail("Build AB", "Build Fail", "OK");
        }
        EditorUtility.ClearProgressBar();
        AssetDatabase.Refresh();
        Debug.Log("Build Succeed !!!");
    }
    /// <summary>
    /// 清除AssetBundle
    /// </summary>
    public static void ClearAssetBundleName()
    {
        string[] strs = AssetDatabase.GetAllAssetBundleNames();
        foreach (var bundleName in strs)
        {
            AssetDatabase.RemoveAssetBundleName(bundleName, true);
        }
        AssetDatabase.Refresh();
    }
    /// <summary>
    /// 检查文件
    /// </summary>
    /// <param name="path"></param>
    private static void Pack(string path)
    {
        DirectoryInfo infos = new DirectoryInfo(path);
        FileSystemInfo[] files = infos.GetFileSystemInfos();
        for (int i = 0; i < files.Length; i++)
        {
            if (files[i] is DirectoryInfo)
            {
                Pack(files[i].FullName);
            }
            else
            {
                if (!files[i].FullName.EndsWith(".meta"))
                {
                    SetAssetBundleName(files[i].FullName);
                }
            }
        }
    }

    /// <summary>
    /// 删除掉当前路径下所有.Manifest文件
    /// </summary>
    /// <param name="path"></param>
    private static void DeleteManifestFile(string path)
    {
        DirectoryInfo infos = new DirectoryInfo(path);
        FileSystemInfo[] files = infos.GetFileSystemInfos();
        for (int i = 0; i < files.Length; i++)
        {
            if (files[i] is DirectoryInfo)
            {
                DeleteManifestFile(files[i].FullName);
            }
            else
            {
                if (files[i].FullName.EndsWith(".manifest"))
                {
                    File.Delete(files[i].FullName);
                }
            }
        }
    }

    /// <summary>
    /// 设置AssetBundleName
    /// </summary>
    /// <param name="source"></param>
    private static void SetAssetBundleName(string source)
    {
        string _source = source.Replace(@"\\", "/");
        //截取完整路径到Assets/位置获得Assets路径
        string _assetPath1 = "Assets" + _source.Substring(Application.dataPath.Length);
        //获取Assets/之后的路径 以方便做AssetBunndleName使用
        string _assetPath2 = _source.Substring(Application.dataPath.Length + 1);
        //获取Assets路径下的文件
        AssetImporter assetImporter = AssetImporter.GetAtPath(_assetPath1);
        //获取AssetBundleName
        string bundleName = _assetPath2;
        //获取文件的扩展名并将其替换成.assetbundle
        bundleName = bundleName.Replace(Path.GetExtension(bundleName), ".assetbundle");
        //设置Bundle名
        assetImporter.assetBundleName = bundleName;
        //获取每个文件的指定路径并添加到列表里以方便写file文件使用
        string newFilePath = m_BundlePutPath + PathUtils.GetRelativePath(source, Application.dataPath, "").ToLower();
        string[] strs = newFilePath.Split('.');
        finalFiles.Add(strs[0] + ".assetbundle");
    }

    /// <summary>
    /// 生成 file 文件
    /// </summary>
    static void CreateFileList()
    {
        //files文件 目标路径
        string targetFilePath = m_BundlePutPath + "/files.txt";
        //检查是否存在该文件 存在则删除
        if (File.Exists(targetFilePath))
            File.Delete(targetFilePath);
        //统计大小 单位B
        long totalFileSize = 0;
        FileStream fs = new FileStream(targetFilePath, FileMode.CreateNew);
        StreamWriter sw = new StreamWriter(fs);
        int count = 0;
        string file;
        finalFiles.Add(m_BundlePutPath + "/AssetBundles");
        File.Delete(m_BundlePutPath + "/AssetBundles.manifest");
        m_BundlePutPath = m_BundlePutPath.Replace('\\', '/');
        foreach (var files in finalFiles)
        {
            file = PathUtils.NormalizePath(files);
            count++;
            Util.UpdateProgress(count, finalFiles.Count + 1, "Createing files.txt");
            //文件Hash
            string hash = "";
            //取到文件路径
            string _path = file.Replace(m_BundlePutPath + "/", string.Empty);
            FileInfo fi = new FileInfo(file);
            if (Path.GetExtension(file) == ".assetbundle")
            {
                //取到文件在Manifest中引用名字
                string abname = file.Replace(m_BundlePutPath + "/", "");
                //通过引用名字去Manifest文件中获取到该文件的Hash值
                hash = m_Manifest.GetAssetBundleHash(abname).ToString();
            }
            else
            {
                hash = Util.md5file(file);
            }
            totalFileSize += fi.Length;
            //将文件信息按行写入到files文件中 路径|Hash|文件大小(单位B)
            sw.WriteLine(_path + "|" + hash + "|" + fi.Length);
        }
        //最后写入总大小(单位B)
        sw.WriteLine("" + totalFileSize);
        sw.Close();
        fs.Close();
    }
}
using System;
using System.IO;
using System.Text;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class Util {
    /// <summary>
    /// 计算文件的MD5值
    /// </summary>
    public static string md5file(string file)
    {
        try
        {
            FileStream fs = new FileStream(file, FileMode.Open);
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(fs);
            fs.Close();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
        catch (Exception ex)
        {
            throw new Exception("md5file() fail, error:" + ex.Message);
        }
    }

#if UNITY_EDITOR
    public static void BuildSuccessOrFail(string tittle,string message,string okmsg)
    {
        EditorUtility.DisplayDialog(tittle, message, okmsg);
    }

    /// <summary>
    /// Updates the progress.更新进度跳
    /// </summary>
    public static void UpdateProgress(int progress, int progressMax, string desc)
    {
        string title = "Processing...[" + progress + " - " + progressMax + "]";
        float value = (float)progress / (float)progressMax;
        EditorUtility.DisplayProgressBar(title, desc, value);
    }
#endif

}
using System.Collections.Generic;
using System.IO;
using UnityEngine;

/// <summary>
/// Path utils.路径工具类
/// </summary>
public class PathUtils {

    /// <summary>
    /// 根据一个绝对路径 获得这个资源的assetbundle name
    /// </summary>
    /// <param name="path"></param>
    /// <param name="root">资源文件夹的根目录</param>
    /// <returns></returns>
    public static string GetAssetBundleNameWithPath(string path,string root)
    {
        string str = NormalizePath(path );
        str = ReplaceFirst(str, root + "/", "");
        return str;
    }

    /// <summary>
    /// 获取文件夹的所有文件,包括子文件夹 不包含.meta文件
    /// </summary>
    /// <returns>The files.</returns>
    /// <param name="path">Path.</param>
    public static FileInfo[] GetFiles(string path)
    {
        DirectoryInfo folder = new DirectoryInfo(path);

        DirectoryInfo[] subFolders = folder.GetDirectories();
        List<FileInfo> filesList = new List<FileInfo>();

        foreach (DirectoryInfo subFolder in subFolders)
        {
            filesList.AddRange(GetFiles(subFolder.FullName));
        }

        FileInfo[] files = folder.GetFiles();
        foreach (FileInfo file in files)
        {
            if (file.Extension != ".meta")
            {
                filesList.Add(file);
            }

        }
        return filesList.ToArray();
    }
    /// <summary>
    /// 获取文件夹的所有文件路径,包括子文件夹 不包含.meta文件
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static string[] GetFilesPath(string path)
    {
        DirectoryInfo folder = new DirectoryInfo(path);
        DirectoryInfo[] subFolders = folder.GetDirectories();
        List<string> filesList = new List<string>();

        foreach (DirectoryInfo subFolder in subFolders)
        {
            filesList.AddRange(GetFilesPath(subFolder.FullName));
        }

        FileInfo[] files = folder.GetFiles();
        foreach (FileInfo file in files)
        {
            if (file.Extension != ".meta")
            {
                filesList.Add(NormalizePath(file.FullName));
            }

        }
        return filesList.ToArray();
    }

    /// <summary>
    /// 创建文件目录前的文件夹,保证创建文件的时候不会出现文件夹不存在的情况
    /// </summary>
    /// <param name="path"></param>
    public static void CreateFolderByFilePath(string path)
    {
        FileInfo fi = new FileInfo(path);
        DirectoryInfo dir = fi.Directory;
        if (!dir.Exists)
        {
            dir.Create();
        }
    }

    /// <summary>
    /// 创建文件夹
    /// </summary>
    /// <param name="path"></param>
    public static void CreateFolder(string path)
    {
        DirectoryInfo dir = new DirectoryInfo(path);
        if (!dir.Exists)
        {
            dir.Create();
        }
    }

    /// <summary>
    /// Deletes the file.删除文件
    /// </summary>
    /// <param name="path">Path.</param>
    public static void DeleteFile(string path) 
    {
        if (File.Exists(path)) File.Delete(path);
    }

    /// <summary>
    /// 规范化路径名称 修正路径中的正反斜杠
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static string NormalizePath(string path)
    {
        return path.Replace(@"\", "/");
    }

    /// <summary>
    /// //将绝对路径转成工作空间内的相对路径
    /// </summary>
    /// <param name="fullPath"></param>
    /// <returns></returns>
    public static string GetRelativePath(string fullPath,string root,string insert = "Assets")
    {
        string path = NormalizePath(fullPath);
        path = ReplaceFirst(path, root, insert);
        return path;
    }
    /// <summary>
    /// 将相对路径转成绝对路径
    /// </summary>
    /// <param name="relativePath"></param>
    /// <returns></returns>
    public static string GetAbsolutelyPath(string relativePath,string root)
    {
        string path = NormalizePath(relativePath);
        path = ReplaceFirst(root, "Assets", "") + path;
        return path;
    }

    /// <summary>
    /// 替换掉第一个遇到的指定字符串
    /// </summary>
    /// <param name="str"></param>
    /// <param name="oldValue"></param>
    /// <param name="newValue"></param>
    /// <returns></returns>
    public static string ReplaceFirst(string str, string oldValue, string newValue)
    {
        int i = str.IndexOf(oldValue);
        str = str.Remove(i, oldValue.Length);
        str = str.Insert(i, newValue);
        return str;
    }

    /// <summary>
    /// Copies the folder to.从一个目录将其内容复制到另一目录
    /// </summary>
    /// <param name="directorySource">Directory source.</param>
    /// <param name="directoryTarget">Directory target.</param>
    public static void CopyFolderTo(string directorySource, string directoryTarget)
    {
        //检查是否存在目的目录
        if (!Directory.Exists(directoryTarget))
        {
            Directory.CreateDirectory(directoryTarget);
        }
        //先来复制文件
        DirectoryInfo directoryInfo = new DirectoryInfo(directorySource);
        FileInfo[] files = directoryInfo.GetFiles();
        //复制所有文件
        foreach (FileInfo file in files)
        {
            file.CopyTo(Path.Combine(directoryTarget, file.Name));
        }
        //最后复制目录
        DirectoryInfo[] directoryInfoArray = directoryInfo.GetDirectories();
        foreach (DirectoryInfo dir in directoryInfoArray)
        {
            CopyFolderTo(Path.Combine(directorySource, dir.Name), Path.Combine(directoryTarget, dir.Name));
        }
    }

    /// <summary>
    /// Creates the stream dir.创建路径
    /// </summary>
    /// <returns>The stream dir.</returns>
    /// <param name="dir">Dir.</param>
    public static string CreateStreamDir(string dir)
    {
        string path = Application.streamingAssetsPath + "/" + dir;

        if (!File.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        return path;
    }


    /// <summary>
    /// Gets all dirs.获取文件路径
    /// </summary>
    /// <param name="dir">Dir.</param>
    /// <param name="list">List.</param>
    public static void GetAllDirs(string dir, List<string> list)
    {
        string[] dirs = Directory.GetDirectories(dir);
        list.AddRange(dirs);

        for (int i = 0; i < dirs.Length; i++)
        {
            GetAllDirs(dirs[i], list);
        }
    }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Unity AssetBundle 打包策略可以分为两种: 1. 依赖关系分离:把项目中的资源按照依赖关系分离到不同的 AssetBundle 中,使得每个 AssetBundle 只包含自己需要的资源,这样可以提高加载性能和空间利用率。 2. 按场景分离:把项目中的资源按照场景分离到不同的 AssetBundle 中,使得每个场景只加载自己需要的资源,这样可以减小加载时间和内存占用。 ### 回答2: Unity AssetBundleUnity 引擎中用于打包资源的一种方式。使用 AssetBundle 可以将游戏中的资源(如模型、纹理、音效等)打包成一个个独立的文件,以便于游戏的动态加载。 AssetBundle打包策略是非常重要的,它直接影响着游戏的加载速度和性能。以下是一些常见的 AssetBundle 打包策略: 1. 按场景打包:将每个场景所需的资源打成一个 AssetBundle。这种打包策略可以减少加载时间,但会增加包的数量和大小。 2. 按功能打包:将同一类型的资源打成一个 AssetBundle。比如把所有的音效打成一个包,把所有的人物模型打成一个包等。这种打包策略可以减少包的数量,但是加载时间可能会变长。 3. 按优先级打包:将优先加载的资源打成一个 AssetBundle,其余资源打成另一个 AssetBundle。这种打包策略可以加速游戏的启动时间,但是可能会影响游戏的流畅度。 4. 动态加载:将一些不常用的资源不打包进游戏,而是在需要的时候再动态加载。这种打包策略可以减少包的大小,但需要注意资源加载和卸载的时机,以免影响游戏的性能。 除了以上的打包策略,还有一些注意事项: 1. 避免重复打包:如果一个资源在多个 AssetBundle 中出现,会造成资源重复加载的问题。所以需要在打包时注意避免重复打包。 2. 多平台适配:不同平台的资源是不一样的,需要为不同平台打不同的包。 3. 版本控制:每个 AssetBundle 都有一个版本号,在更新游戏时需要根据版本号进行更新,以免出现版本不一致的问题。 总之,在打包 AssetBundle 时需要考虑到包的数量、大小、加载速度、游戏流畅度等多个因素。合理的打包策略可以提高游戏的性能和用户体验。 ### 回答3: Unity AssetBundleUnity引擎中的一项重要功能,可以将资源打包为AssetBundle,用于开发过程中的资源管理和动态下载等。那么,我们在打包AssetBundle时应该有哪些策略呢? 1. 前期资源规划:首先需在项目开始前做出合理的资源规划,以期望达到合理性和可维护性。在资源规划中,应该对每个场景和资源类型进行详细的分类、拆分,确定其相关性,以确保资源包的规范和稳定性。 2. 打包结构优化:在打包AssetBundle时,应考虑资源包的规范、可维护性和性能。对于同类资源进行打包,优先考虑动态资源和重要资源。同时,在打包模式和资源指定上也应该考虑在层级和粒度上细分。 3. 小包原则:AssetBundle应该尽可能地小,避免将无关资源打包到一起,同时尽可能避免多个AssetBundle有所依赖。 4. 缓存优化:合理使用缓存,如资源缓存的动态切换、组合等策略。可以缓存一些常用的资源,以避免频繁的网络请求,同时也要考虑缓存内存大小和清理策略。 5. 资源版本管理:由于资源的更新可能会对AssetBundle产生影响,因此需要将资源版本号和AssetBundle打包版本号进行关联。在资源变化时,需要更新AssetBundle版本,并及时更新客户端中的AssetBundle。 6. 安全策略:保护和控制AssetBundle的读写权限,确保AssetBundle不被非法修改和文件篡改。同时要处理AssetBundle加密和解密,以确保网络传输的数据不被盗取和破解。 Unity AssetBundle打包策略是开发中必备的一项技术,旨在提高项目的可维护性、性能和安全。在实际项目中,需要根据具体情况来决定如何合理使用AssetBundle,以达到最佳效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小张不爱写代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值