Unity 5.X 打包AssetBundles

Editor下创建脚本CreateAssetBundles

using UnityEngine;
using UnityEditor;
using System.IO;

public class CreateAssetBundles : Editor
{

    [MenuItem("Tools/Build AssetBundles")]
    static void BuildAllAssetBundles()
    {
        BuildPipeline.BuildAssetBundles(Application.dataPath + "/AssetBundles", BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.Android);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
        Debug.LogWarning("打包成功");
    }

    [MenuItem("Tools/设置固定名")]
    public static void saveAsStaticName()
    {
        string Path = "Prefabs";
        string abName = "building.ab";
        SetVersionDirAssetName(Path, abName);//第一个参数是路径 第二个参数是Ab名字 默认前缀为 Application.dataPath + "/"+ Path  
    }

    [MenuItem("Tools/设定文件名")]
    public static void saveAsPrefabName()
    {
        string Path = "Prefabs";
        SetAssetNameAsPrefabName(Path);//第一个参数是路径   
    }

    public static void SetVersionDirAssetName(string fullPath, string abName)
    {
        var relativeLen = fullPath.Length + 8; // Assets 长度  
        fullPath = Application.dataPath + "/" + fullPath + "/";

        if (Directory.Exists(fullPath))
        {
            EditorUtility.DisplayProgressBar("设置AssetName名称", "正在设置AssetName名称中...", 0f);
            var dir = new DirectoryInfo(fullPath);
            var files = dir.GetFiles("*", SearchOption.AllDirectories);
            for (var i = 0; i < files.Length; ++i)
            {
                var fileInfo = files[i];
                EditorUtility.DisplayProgressBar("设置AssetName名称", "正在设置AssetName名称中...", 1f * i / files.Length);
                if (!fileInfo.Name.EndsWith(".meta"))
                {
                    var basePath = fileInfo.FullName.Substring(fullPath.Length - relativeLen);//.Replace('\\', '/');  
                    var importer = AssetImporter.GetAtPath(basePath);
                    if (importer && importer.assetBundleName != abName)
                    {
                        importer.assetBundleName = abName;
                    }
                }
            }
            EditorUtility.ClearProgressBar();
        }
    }

    public static void SetAssetNameAsPrefabName(string fullPath)
    {
        var relativeLen = fullPath.Length + 8; // Assets 长度  
        fullPath = Application.dataPath + "/" + fullPath + "/";

        if (Directory.Exists(fullPath))
        {
            EditorUtility.DisplayProgressBar("设置AssetName名称", "正在设置AssetName名称中...", 0f);
            var dir = new DirectoryInfo(fullPath);
            var files = dir.GetFiles("*", SearchOption.AllDirectories);
            for (var i = 0; i < files.Length; ++i)
            {
                var fileInfo = files[i];
                string abName = fileInfo.Name;
                EditorUtility.DisplayProgressBar("设置AssetName名称", "正在设置AssetName名称中...", 1f * i / files.Length);
                if (!fileInfo.Name.EndsWith(".meta"))
                {
                    var basePath = fileInfo.FullName.Substring(fullPath.Length - relativeLen);//.Replace('\\', '/');  
                    var importer = AssetImporter.GetAtPath(basePath);
                    //abName = AssetDatabase.AssetPathToGUID(basePath);
                    if (importer && importer.assetBundleName != abName)
                    {
                        importer.assetBundleName = abName;
                    }
                }
            }
            EditorUtility.ClearProgressBar();
        }
    }

    /// <summary>  
    /// AssetBundleManifestName == 对应AB依赖列表文件  
    /// </summary>  

    private static string AssetBundle_BuildDirectory_Path = @Application.streamingAssetsPath + "/../../../" + "AssetBundles";
    private static string AssetBundle_TargetDirectory_Path = @Application.streamingAssetsPath + "/" + "ABFiles";
    [MenuItem("Tools/Asset Bundle/Build Asset Bundles", false, 0)]
    public static void BuildAssetBundleAndroid()
    {
        //Application.streamingAssetsPath对应的StreamingAssets的子目录  
        DirectoryInfo AB_Directory = new DirectoryInfo(AssetBundle_BuildDirectory_Path);
        if (!AB_Directory.Exists)
        {
            AB_Directory.Create();
        }
        FileInfo[] filesAB = AB_Directory.GetFiles();
        foreach (var item in filesAB)
        {
            Debug.Log("******删除旧文件:" + item.FullName + "******");
            item.Delete();
        }
#if UNITY_ANDROID
        BuildPipeline.BuildAssetBundles(AB_Directory.FullName, BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.Android);  
#elif UNITY_IPHONE
        BuildPipeline.BuildAssetBundles(AB_Directory.FullName, BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.iOS); 
#else
        BuildPipeline.BuildAssetBundles(AB_Directory.FullName, BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.StandaloneWindows64);
#endif
        Debug.Log("******AssetBundle打包完成******");

        Debug.Log("将要转移的文件夹是:" + AssetBundle_TargetDirectory_Path);
        FileInfo[] filesAB_temp = AB_Directory.GetFiles();

        DirectoryInfo streaming_Directory = new DirectoryInfo(AssetBundle_TargetDirectory_Path);

        FileInfo[] streaming_files = streaming_Directory.GetFiles();
        foreach (var item in streaming_files)
        {
            item.Delete();
        }
        AssetDatabase.Refresh();
        foreach (var item in filesAB_temp)
        {
            if (item.Extension == "")
            {
                item.CopyTo(AssetBundle_TargetDirectory_Path + "/" + item.Name, true);
            }
        }
        AssetDatabase.Refresh();
        Debug.Log("******文件传输完成******");
    }

    private static string _dirName = "";
    /// <summary>  
    /// 批量命名所选文件夹下资源的AssetBundleName.  
    /// </summary>  
    [MenuItem("Tools/Asset Bundle/Set Asset Bundle Name")]
    static void SetSelectFolderFileBundleName()
    {
        UnityEngine.Object[] selObj = Selection.GetFiltered(typeof(Object), SelectionMode.Unfiltered);
        foreach (Object item in selObj)
        {
            string objPath = AssetDatabase.GetAssetPath(item);
            DirectoryInfo dirInfo = new DirectoryInfo(objPath);
            if (dirInfo == null)
            {
                Debug.LogError("******请检查,是否选中了非文件夹对象******");
                return;
            }
            _dirName = dirInfo.Name;

            string filePath = dirInfo.FullName.Replace('\\', '/');
            filePath = filePath.Replace(Application.dataPath, "Assets");
            AssetImporter ai = AssetImporter.GetAtPath(filePath);
            ai.assetBundleName = _dirName;

            SetAssetBundleName(dirInfo);
        }
        AssetDatabase.Refresh();
        Debug.Log("******批量设置AssetBundle名称成功******");
    }
    static void SetAssetBundleName(DirectoryInfo dirInfo)
    {
        FileSystemInfo[] files = dirInfo.GetFileSystemInfos();
        foreach (FileSystemInfo file in files)
        {
            if (file is FileInfo && file.Extension != ".meta" && file.Extension != ".txt")
            {
                string filePath = file.FullName.Replace('\\', '/');
                filePath = filePath.Replace(Application.dataPath, "Assets");
                AssetImporter ai = AssetImporter.GetAtPath(filePath);
                ai.assetBundleName = _dirName;
            }
            else if (file is DirectoryInfo)
            {
                string filePath = file.FullName.Replace('\\', '/');
                filePath = filePath.Replace(Application.dataPath, "Assets");
                AssetImporter ai = AssetImporter.GetAtPath(filePath);
                ai.assetBundleName = _dirName;
                SetAssetBundleName(file as DirectoryInfo);
            }
        }
    }
    /// <summary>  
    /// 批量清空所选文件夹下资源的AssetBundleName.  
    /// </summary>  
    [MenuItem("Tools/Asset Bundle/Reset Asset Bundle Name")]
    static void ResetSelectFolderFileBundleName()
    {
        UnityEngine.Object[] selObj = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Unfiltered);
        foreach (UnityEngine.Object item in selObj)
        {
            string objPath = AssetDatabase.GetAssetPath(item);
            DirectoryInfo dirInfo = new DirectoryInfo(objPath);
            if (dirInfo == null)
            {
                Debug.LogError("******请检查,是否选中了非文件夹对象******");
                return;
            }
            _dirName = null;

            string filePath = dirInfo.FullName.Replace('\\', '/');
            filePath = filePath.Replace(Application.dataPath, "Assets");
            AssetImporter ai = AssetImporter.GetAtPath(filePath);
            ai.assetBundleName = _dirName;

            SetAssetBundleName(dirInfo);
        }
        AssetDatabase.Refresh();
        Debug.Log("******批量清除AssetBundle名称成功******");
    }
}

创建脚本TestAssetBundle挂在到场景

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestAssetBundle : MonoBehaviour
{

    public string AssetBundleName = "building.ab";

	public string AssetName= "Sphere";

    private string dir = "";
    private AssetBundle bundle = null;
    private Object asset = null;
    private GameObject go = null;

    private AssetBundleManifest manifest = null;

    // Use this for initialization
    void Start()
    {
        dir = Application.dataPath + "/AssetBundles/";
    }

    void OnGUI()
    {
        if (GUILayout.Button("LoadAssetBundle", GUILayout.Width(200), GUILayout.Height(50))) { LoadBundle(); }
        if (GUILayout.Button("LoadAsset", GUILayout.Width(200), GUILayout.Height(50))) { LoadAsset(); }
        if (GUILayout.Button("Instantiate", GUILayout.Width(200), GUILayout.Height(50))) { Instantiate(); }
        if (GUILayout.Button("Destory", GUILayout.Width(200), GUILayout.Height(50))) { Destroy(); }
        if (GUILayout.Button("Unload", GUILayout.Width(200), GUILayout.Height(50))) { UnLoad(); }
        if (GUILayout.Button("UnloadForce", GUILayout.Width(200), GUILayout.Height(50))) { UnLoadForce(); }
        if (GUILayout.Button("UnloadUnusedAssets", GUILayout.Width(200), GUILayout.Height(50))) { UnloadUnusedAssets(); }

        //bundle依赖包加载
        if (GUILayout.Button("LoadAssetBundleManifest", GUILayout.Width(200), GUILayout.Height(50))) { LoadAssetBundleManifest(); }
        if (GUILayout.Button("LoadBundleAndDeps", GUILayout.Width(200), GUILayout.Height(50))) { LoadBundleAndDeps(); }
    }

    void LoadBundle()
    {
        bundle = AssetBundle.LoadFromFile(System.IO.Path.Combine(dir, AssetBundleName));
        if (null == bundle)
        {
            Debug.LogError("LoadBundle Failed");
        }
    }

    void LoadAsset()
    {
        if (null == bundle) return;
		GameObject[] objs = bundle.LoadAllAssets<GameObject>();
		Debug.Log ("obj counts is "+objs.Length);
		for (int i = 0; i < objs.Length; i++) {
			Debug.Log (objs[i].name);
		}
		asset = bundle.LoadAsset<GameObject>(AssetName);
        if (null == asset) Debug.LogError("LoadAsset Failed");
    }

    void Instantiate()
    {
        if (null == asset) return;

        go = GameObject.Instantiate<Object>(asset) as GameObject;
        if (null == go) Debug.LogError("Instantiate Failed");
        else
        {
            //go.transform.SetParent(GameObject.Find("UIRoot").transform);
        }
    }

    void Destroy()
    {
        if (null == go) return;

        GameObject.Destroy(go);
        go = null;
    }

    /**
     *  AssetBundle.unload(bool unloadAllLoadedObjects) 接口用来卸载AssetBundle文件。
     *  参数为false时,调用该接口后,只会卸载AssetBundle对象自身,并不会影响AssetBundle中加载的Assets。
     *  参数为true时,除了AssetBundle对象自身,所有从当前AssetBundle中加载的Assets也会被同时卸载,不管这个Assets是否还在使用中。
     *  官方推荐参数一般设置为false,只有当很明确知道从AssetsBundle中加载的Assets不会被任何对象引用时,才将参数设置成true。
     **/
    void UnLoad()
    {
        if (null == bundle) return;

        bundle.Unload(false);
        //GameObject.Instantiate<Object>(asset);  //asset可用
        asset = null;
        bundle = null;
    }

    void UnLoadForce()
    {
        if (null == bundle) return;

        bundle.Unload(true);
        //GameObject.Instantiate<Object>(asset);  //报错:asset已被销毁
        asset = null;
        bundle = null;
    }

    void UnloadUnusedAssets()
    {
        Resources.UnloadUnusedAssets();
    }

    void LoadAssetBundleManifest()
    {
        var bundle = AssetBundle.LoadFromFile(System.IO.Path.Combine(dir, "AssetBundles"));
        manifest = bundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");

        //unload
        bundle.Unload(false);
        bundle = null;
    }

    void LoadBundleAndDeps()
    {
        string bundleName = "cube";

        string[] dependence = manifest.GetDirectDependencies(bundleName);
        for (int i = 0; i < dependence.Length; ++i)
        {
            AssetBundle.LoadFromFile(System.IO.Path.Combine(dir, dependence[i]));
        }

        var bundle = AssetBundle.LoadFromFile(System.IO.Path.Combine(dir, bundleName));
        var asset = bundle.LoadAsset<GameObject>("Cube");
        bundle.Unload(false);
        bundle = null;
        go = GameObject.Instantiate<GameObject>(asset);
    }
}

ABDownload  下载AB包

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

public class ABDownload : MonoBehaviour
{


    string _url_1 = "http://XXX/building.ab.manifest";
    string _url_2 = "http://XXX/building.ab";
    string _Name_1 = "building.ab.manifest";
    string _Name_2 = "building.ab";

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Z))
        {
            StartCoroutine(DownloadAndSave(_url_1, _Name_1));
        }
        if (Input.GetKeyDown(KeyCode.X))
        {
            StartCoroutine(DownloadAndSave(_url_2, _Name_2));
        }
        
    }

    /// <summary>  
    /// 下载并保存资源到本地  
    /// </summary>  
    /// <param name="url"></param>  
    /// <param name="name"></param>  
    /// <returns></returns>  
    public static IEnumerator DownloadAndSave(string url, string name, Action<bool, string> Finish = null)
    {
        url = Uri.EscapeUriString(url);
        string Loading = string.Empty;
        bool b = false;
        WWW www = new WWW(url);
        if (www.error != null)
        {
            print("error:" + www.error);
        }
        while (!www.isDone)
        {
            Loading = (((int)(www.progress * 100)) % 100) + "%";
            if (Finish != null)
            {
                Finish(b, Loading);
            }
            yield return 1;
        }
        if (www.isDone)
        {
            Loading = "100%";
            byte[] bytes = www.bytes;
            b = SaveAssets(Application.dataPath + "/AssetBundles/", name, bytes);
            if (Finish != null)
            {
                Finish(b, Loading);
            }
        }
        Debug.Log(Loading);
    }

    /// <summary>  
    /// 保存资源到本地  
    /// </summary>  
    /// <param name="path"></param>  
    /// <param name="name"></param>  
    /// <param name="info"></param>  
    /// <param name="length"></param>  
    public static bool SaveAssets(string path, string name, byte[] bytes)
    {
        Stream sw;
        FileInfo t = new FileInfo(path + "//" + name);
        if (!t.Exists)
        {
            try
            {
                sw = t.Create();
                sw.Write(bytes, 0, bytes.Length);
                sw.Close();
                sw.Dispose();
                return true;
            }
            catch
            {
                return false;
            }
        }
        else
        {
            return true;
        }
    }

}

打到一个AB包的话,每个预制体AssetBundle名字必须是building.ab,就是上面的右下角位置。

 

 

打包位置默认位置Prefabs文件夹。

原文:https://blog.csdn.net/abcd5711664321/article/details/82253392

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
对于Unity5.x升级到Unity2017.x的过程中常见的异常问题,可以参考整理的经验共享文档。另外,如果您需要下载Unity5.x的32位版本,可以通过修改下载链接中的数字64为32来获取相应的安装程序。此外,您还可以关注Unity官方的GitHub页面,那里会发布一些示例工程以及处于开发阶段的新功能,可以帮助您了解Unity的发展方向并提升开发技能。希望这些信息对您有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Unity4.x/5.x/2017.x升级差异总结](https://blog.csdn.net/weixin_34206899/article/details/86085382)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [最全UnityHub国际版下载链接Unity2023~2017各版本+Unity5.x【间歇性更新】](https://blog.csdn.net/qq_36829186/article/details/123847081)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [unity 5.x从入门到精通_Unity学习中值得收藏的学习资料(书籍)与博客](https://blog.csdn.net/u013712343/article/details/123378759)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

奇大可

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

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

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

打赏作者

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

抵扣说明:

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

余额充值