unity傻瓜式打包assetsbundle(二)

制作assetbundle是手游的必备技能,作者在这里分享一下自己写的用的工具类

根据当前项目选择的平台,打包对应的资源包,并保存assetsbundle的相关信息进json文件里

可以在tool这里选择打包resource下的资源(代码可以修改为其他目录,已经作为常量,便于修改)

unity傻瓜式打包assetsbundle(二)_第1张图片

也可以在project面板里选择具体的文件夹右键

unity傻瓜式打包assetsbundle(二)_第2张图片

那么他就会打包在StreamingAssets里

unity傻瓜式打包assetsbundle(二)_第3张图片

贴一下代码,主要的类,这个类需要放在Assets/Editor的目录下

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework.Constraints;
using UnityEditor;
using UnityEngine;
using LitJson;

public class BuildAssetsBundle : Editor
{
    private const string BuildAssetsBundleMenuAll = "Tools/BuildAssetsBundle";
    private const string BuildAssetsBundleMenu = "Assets/BuildAssetsBundle";
    private static List assetNames = new List();
    /// 
    /// 打包assetsbundle的源文件的文件夹
    /// 
    private static string OriginalDirectory = Application.dataPath + "/Resources/";
    /// 
    /// 打出包的输出文件夹
    /// 
    private static string OutDirectory = "Assets/StreamingAssets/AssetsBundle/";
    private const string ConfigFile = "Assets/StreamingAssets/AssetsBundle/AssetsBundleConfig.Config";
    //配置文件json,对应的对象实例    
    private static AssetsBundleConfig config = null;
    #region  打assets包
    /// 
    /// 打包Assets/package目录下的所有文件为bundle包
    /// 
    [MenuItem(BuildAssetsBundleMenuAll)]
    public static void BuildAssetsBundleAll()
    {
        DirectoryInfo info = new DirectoryInfo(OriginalDirectory);
        DirectoryInfo[] infos = info.GetDirectories();
        GetConfig();
        for (int i = 0; i < infos.Length; i++)
        {
            var name = infos[i].Name;
            FindAllFile(OriginalDirectory + name + "/", name);
        }
        OutPutConfig();
    }
    //根据具体文件夹打包assetsbundle
    [MenuItem(BuildAssetsBundleMenu, false, 1)]
    public static void BuildAssetsB()
    {
        var paths = Selection.assetGUIDs.Select(AssetDatabase.GUIDToAssetPath).Where(AssetDatabase.IsValidFolder).ToList();
        if (paths.Count > 1)
        {
            EditorUtility.DisplayDialog("", "不能同时选择多个目录进行该操作!", "确定");
            return;
        }
        var strName = paths[0].Split('/');
        GetConfig();
        FindAllFile(paths[0], strName[strName.Length - 1]);
        OutPutConfig();
    }
    static void FindAllFile(string path, string assetsBundlename)
    {
        assetNames.Clear();
        FindFile(path);
        CreateAssetBunlde(assetsBundlename);
    }
    static void FindFile(string assetBundleName)
    {
        DirectoryInfo di = new DirectoryInfo(assetBundleName);

        FileInfo[] fis = di.GetFiles();
        for (int i = 0; i < fis.Length; i++)
        {
            if (fis[i].Extension != ".meta")
            {
                string str = fis[i].FullName;
                assetNames.Add(str.Substring(str.LastIndexOf("Assets")));
            }
        }
        DirectoryInfo[] dis = di.GetDirectories();
        for (int j = 0; j < dis.Length; j++)
        {
            FindFile(dis[j].FullName);
        }
    }
    /// 
    /// 每次打包assetsbundle的前要获取整个配置文件
    /// 
    static void GetConfig()
    {
        config = null;
        var bytes = FileTools.TryReadFile(ConfigFile);
        config = (bytes == null) ? new AssetsBundleConfig() : JsonMapper.ToObject(Encoding.UTF8.GetString(bytes));
    }
    /// 
    /// 打包好了,要输出配置文件
    /// 
    static void OutPutConfig()
    {
        if (config != null && config.AssetsBundles != null & config.AssetsBundles.Count > 0)
        {
            var content = JsonMapper.ToJson(config);
            FileTools.TryWriteFile(ConfigFile, content);
        }
        AssetDatabase.Refresh();
    }
    /// 
    /// 打包资源到StreamingAssets下对应的平台,对应的资源名
    /// 
    /// 
    static void CreateAssetBunlde(string assetBundleName)
    {
        string[] assetBundleNames = assetNames.ToArray();
        AssetBundleBuild[] abs = new AssetBundleBuild[1];
        abs[0].assetNames = assetBundleNames;
        abs[0].assetBundleName = assetBundleName + ".assetBundle";
        BuildTarget buildTarget;
        string outPutPlat;
#if UNITY_ANDROID   //安卓  
        buildTarget = BuildTarget.Android;
        outPutPlat = "Android";
#elif UNITY_IOS
        buildTarget = BuildTarget.iOS;
        outPutPlat = "IOS";
#else
        buildTarget = BuildTarget.StandaloneWindows;
        outPutPlat = "Windows";
#endif
        var dicName = OutDirectory + outPutPlat;
        FileTools.EnsureDirectoryExist(dicName);
        AssetBundleManifest mainfest = BuildPipeline.BuildAssetBundles(dicName, abs, BuildAssetBundleOptions.None, buildTarget);
        var filepath = dicName + "/" + abs[0].assetBundleName;
        var size = (int)FileTools.TryGetFileSize(filepath);
        var assets = CreateAssets(assetBundleName, outPutPlat, size);
        if (config.AssetsBundles != null && config.AssetsBundles.Count > 0)
        {
            for (int i = 0; i < config.AssetsBundles.Count; i++)
            {
                var havedAssets = config.AssetsBundles[i];
                if ((havedAssets.name == assets.name) && (havedAssets.platform == assets.platform))
                {
                    config.AssetsBundles.Remove(havedAssets);
                    break;
                }
            }
        }
        config.AssetsBundles.Add(assets);
        Debug.LogError(assetBundleName + "打包完成");
    }
    /// 
    /// 新建assetbundle对应的对象实例
    /// 
    /// 
    /// 
    /// 
    static Assets CreateAssets(string assetBundleName, string platform,int size)
    {
        Assets assets = new Assets();
        assets.name = assetBundleName;
        assets.platform = platform;
        assets.size = size;
        return assets;
    }
    #endregion
}
assetsbundle的实体配置类
using System.Collections.Generic;
using UnityEngine;

/// 
/// AssetsBundleConfig配置文件的映射对象
/// 
[SerializeField]
public class AssetsBundleConfig
{
    [SerializeField]
    public List AssetsBundles;
    public AssetsBundleConfig()
    {
        AssetsBundles = new List();
    }
}
[SerializeField]
public class Assets
{
    /// 
    /// AssetsBundle的名字
    /// 
    [SerializeField]
    public string name;
    /// 
    /// AssetsBundle的大小
    /// 
    [SerializeField]
    public int size;
    /// 
    /// AssetsBundle的所属平台0-window,1-ios,2-android
    /// 
    [SerializeField]
    public string platform;

    public Assets()
    {
    }

    public Assets(string name, int size, string platform)
    {
        this.name = name;
        this.size = size;
        this.platform = platform;
    }
}
操作文件的工具类
using System.Collections;
using System.Collections.Generic;
using System;
using System.Diagnostics;
using System.IO;
using Debug = UnityEngine.Debug;

public class FileTools
{
    /// 
    /// 确保文件夹存在
    /// 
    public static void EnsureDirectoryExist(string targetDir, bool isHide = false)
    {
        if (!Directory.Exists(targetDir))
        {
            Directory.CreateDirectory(targetDir);
            if (isHide)
            {
                File.SetAttributes(targetDir, FileAttributes.Hidden);
            }
        }
    }
    /// 
    /// 尝试着读取文件,小文件
    /// 
    /// 
    /// 
    public static byte[] TryReadFile(string path)
    {
        //文件路径要正确
        if (path.Length < 1)
        {
            return null;
        }
        if (!File.Exists(path))
        {
            Debug.LogError(path+"这个文件没找到");
            return null;
        }
        FileStream fs=new FileStream(path, FileMode.Open, FileAccess.Read);
        if (fs.CanRead)
        {
            byte[]array=new byte[fs.Length];
            fs.Read(array, 0, array.Length);
            fs.Close();
            return array;
        }
        fs.Close();
        return null;
    }
    /// 
    /// 尝试着写东西进一个文件,覆盖原文件
    /// 
    /// 
    /// 
    public static void TryWriteFile(string path,string content)
    {
        if (path.Length<1)
        {
            return;
        }
        using (StreamWriter sw=new StreamWriter(path,false))
        {
           sw.Write(content);
        }
    }

    public static long TryGetFileSize(string path)
    {
        if (path.Length<1)
        {
            return 0;
        }

        FileInfo fi = new FileInfo(path);
        if (fi==null)
        {
            return 0;
        }
        return fi.Length;
    }
}


觉得有用就请我喝杯咖啡吧,哈哈哈

加载assetsbundle的代码,下一篇介绍,敬请期待

unity傻瓜式打包assetsbundle(二)_第4张图片

下载资源点击打开链接

你可能感兴趣的:(unity傻瓜式打包assetsbundle(二))