Unity5 AssetBundle 打包和下载

打包

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

/// <summary>
/// 把Resource下的资源打包成.unity3d 到StreamingAssets目录下
/// </summary>
public class Builder : Editor
{
    public static string sourcePath = Application.dataPath + "/Resources";
    const string AssetBundlesOutputPath = "Assets/StreamingAssets";

    [MenuItem("Tools/AssetBundle/Build")]
    public static void BuildAssetBundle()
    {
        Caching.CleanCache();
        ClearAssetBundlesName();

        Pack(sourcePath);

        string outputPath = Path.Combine(AssetBundlesOutputPath, Platform.GetPlatformFolder(EditorUserBuildSettings.activeBuildTarget));
        if (!Directory.Exists(Application.dataPath + "/../Assetbundle"))
        {
            Directory.CreateDirectory(Application.dataPath + "/../Assetbundle");
        }
        Debug.Log(outputPath);
        //根据BuildSetting里面所激活的平台进行打包
       // BuildPipeline.BuildAssetBundles(outputPath, 0, EditorUserBuildSettings.activeBuildTarget);
        BuildPipeline.BuildAssetBundles(Application.dataPath + "/../Assetbundle", BuildAssetBundleOptions.UncompressedAssetBundle);
        AssetDatabase.Refresh();

        Debug.Log("打包完成");

    }

    /// <summary>
    /// 清除之前设置过的AssetBundleName,避免产生不必要的资源也打包
    /// 之前说过,只要设置了AssetBundleName的,都会进行打包,不论在什么目录下
    /// </summary>
    static void ClearAssetBundlesName()
    {
        int length = AssetDatabase.GetAllAssetBundleNames().Length;
        Debug.Log(length);
        string[] oldAssetBundleNames = new string[length];
        for (int i = 0; i < length; i++)
        {
            oldAssetBundleNames[i] = AssetDatabase.GetAllAssetBundleNames()[i];
        }

        for (int j = 0; j < oldAssetBundleNames.Length; j++)
        {
            AssetDatabase.RemoveAssetBundleName(oldAssetBundleNames[j], true);
        }
        length = AssetDatabase.GetAllAssetBundleNames().Length;
        Debug.Log(length);
    }

    static void Pack(string source)
    {
        DirectoryInfo folder = new DirectoryInfo(source);
        FileSystemInfo[] files = folder.GetFileSystemInfos();
        int length = files.Length;
        for (int i = 0; i < length; i++)
        {
            if (files[i] is DirectoryInfo)
            {
                Pack(files[i].FullName);
            }
            else
            {
                if (!files[i].Name.EndsWith(".meta"))
                {
                    file(files[i].FullName);
                }
            }
        }
    }

    static void file(string source)
    {
        string _source = Replace(source);
        string _assetPath = "Assets" + _source.Substring(Application.dataPath.Length);
        string _assetPath2 = _source.Substring(Application.dataPath.Length + 1);
        //Debug.Log (_assetPath);

        //在代码中给资源设置AssetBundleName
        AssetImporter assetImporter = AssetImporter.GetAtPath(_assetPath);
        string assetName = _assetPath2.Substring(_assetPath2.IndexOf("/") + 1);
        assetName = assetName.Replace(Path.GetExtension(assetName), ".unity3d");
        //Debug.Log (assetName);
        assetImporter.assetBundleName = assetName;
    }

    static string Replace(string s)
    {
        return s.Replace("\\", "/");
    }
}

public class Platform
{
    public static string GetPlatformFolder(BuildTarget target)
    {
        switch (target)
        {
            case BuildTarget.Android:
                return "Android";
            case BuildTarget.iOS:
                return "IOS";
            case BuildTarget.WebPlayer:
                return "WebPlayer";
            case BuildTarget.StandaloneWindows:
            case BuildTarget.StandaloneWindows64:
                return "Windows";
            case BuildTarget.StandaloneOSXIntel:
            case BuildTarget.StandaloneOSXIntel64:
            case BuildTarget.StandaloneOSXUniversal:
                return "OSX";
            default:
                return null;
        }
    }
}
  • 读取

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    
    public class Test : MonoBehaviour
    {
        AssetBundle manifestBundle = null;
        AssetBundle cubeBundle = null;
        private string buildPath = Application.dataPath + "/../Assetbundle/";
    
        public Dictionary<string, AssetBundle> bundleList = new Dictionary<string, AssetBundle>();
        // Use this for initialization
        void Start()
        {
            LoadBundle("");
        }
    
        public void LoadBundle(string name) {
        }
    
        //单独读取资源
        private IEnumerator LoadGameObjectPackedByThemselves(string path)
        {
            Debug.Log(path);
            //WWW bundle = new WWW(path);
            //yield return bundle;
    
            WWW www = WWW.LoadFromCacheOrDownload(path, 5);
            yield return www;
            //加载
            //Instantiate(bundle.assetBundle);
    
            //www.assetBundle.Unload(false);
        }
    
        void OnGUI()
        {
            if (GUILayout.Button("LoadAssetbundle"))
            {
                //首先加载Manifest文件;
                if (bundleList.ContainsKey(buildPath + ResourceConfig.MainAssetBundle))
                {
                    manifestBundle = bundleList[buildPath + ResourceConfig.MainAssetBundle];
                }
                else
                {
                    manifestBundle = AssetBundle.LoadFromFile(buildPath + ResourceConfig.MainAssetBundle);
                    bundleList.Add(buildPath + ResourceConfig.MainAssetBundle, manifestBundle);
                }
    
                //manifestBundle = AssetBundle.LoadFromFile(Application.dataPath + "/../Assetbundle/Assetbundle");
                Debug.Log(buildPath + ResourceConfig.MainAssetBundle);
                if (manifestBundle != null)
                {
                    AssetBundleManifest manifest = (AssetBundleManifest)manifestBundle.LoadAsset("AssetBundleManifest");
                    if (manifest == null) {
                        Debug.Log("manifest == null");
                    }
                    //获取依赖文件列表;
                    string[] cubedepends = manifest.GetAllDependencies(ResourceConfig.BundleTextPrefabPath);
                    AssetBundle[] dependsAssetbundle = new AssetBundle[cubedepends.Length];
    
                    for (int index = 0; index < cubedepends.Length; index++)
                    {
                        //加载所有的依赖文件;
                        if (bundleList.ContainsKey(buildPath + cubedepends[index]))
                        {
                            continue;
                        }
                        dependsAssetbundle[index] = AssetBundle.LoadFromFile(buildPath + cubedepends[index]);
                        bundleList.Add(buildPath + cubedepends[index], dependsAssetbundle[index]);
    
                    }
                    //加载我们需要的文件;
                    if (bundleList.ContainsKey(buildPath + ResourceConfig.BundleTextPrefabPath))
                    {
                        cubeBundle = bundleList[buildPath + ResourceConfig.BundleTextPrefabPath];
                    }
                    else {
                        cubeBundle = AssetBundle.LoadFromFile(buildPath + ResourceConfig.BundleTextPrefabPath);
                        bundleList.Add(buildPath + ResourceConfig.BundleTextPrefabPath , cubeBundle);
                    }
    
                    GameObject cube = cubeBundle.LoadAsset("bundletextprefab") as GameObject;
                    if (cube != null)
                    {
                        //GameObject o = Instantiate(cube);
                        //o.transform.parent = GameObject.Find("Camera").transform;
                        GameObject obj = NGUITools.AddChild(GameObject.Find("Camera"), cube);
                    }
                }
    
            }
        }
    
        public AssetBundle DownBundle(string path) {
    
            if (bundleList.ContainsKey(buildPath + ResourceConfig.MainAssetBundle))
            {
                manifestBundle = bundleList[buildPath + ResourceConfig.MainAssetBundle];
            }
            else
            {
                manifestBundle = AssetBundle.LoadFromFile(buildPath + ResourceConfig.MainAssetBundle);
                bundleList.Add(buildPath + ResourceConfig.MainAssetBundle, manifestBundle);
            }
            if (manifestBundle != null)
            {
                AssetBundleManifest manifest = (AssetBundleManifest)manifestBundle.LoadAsset("AssetBundleManifest");
                if (manifest == null)
                {
                    Debug.Log("manifest == null");
                }
                //获取依赖文件列表;
                string[] cubedepends = manifest.GetAllDependencies(ResourceConfig.IconPath);
                AssetBundle[] dependsAssetbundle = new AssetBundle[cubedepends.Length];
    
                for (int index = 0; index < cubedepends.Length; index++)
                {
                    //加载所有的依赖文件;
                    if (bundleList.ContainsKey(buildPath + cubedepends[index]))
                    {
                        continue;
                    }
                    dependsAssetbundle[index] = AssetBundle.LoadFromFile(buildPath + cubedepends[index]);
                    bundleList.Add(buildPath + cubedepends[index], dependsAssetbundle[index]);
    
                }
    
                //加载我们需要的文件;
                if (bundleList.ContainsKey(buildPath + ResourceConfig.IconPath))
                {
                    cubeBundle = bundleList[buildPath + ResourceConfig.IconPath];
                }
                else
                {
                    cubeBundle = AssetBundle.LoadFromFile(buildPath + ResourceConfig.IconPath);
                    bundleList.Add(buildPath + ResourceConfig.IconPath , cubeBundle);
                }
    
            }
            return cubeBundle;
        }
        public void Removebundle() {
            cubeBundle.Unload(false);
            bundleList.Remove(Application.dataPath + "/../Assetbundle/icon.unity3d");
        }
    }
  • 这里是  我给资源做的一个全局路径记录  用来 加载
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    
    public class ResourceConfig  {
    
        public const string MainAssetBundle = "Assetbundle";
    
        public const string BundleItemPath = "Prefabs/BundleItem.prefab";
        public const string BundleTextPrefabPath = "Prefabs/BundleTextPrefab.prefab";
        public const string item1Path = "item1.prefab";
        public const string itemPath = "item.prefab";
        public const string IconPath = "icon.unity3d";
    
    }
  • 这里是  View层的调用

    using UnityEngine;
    using System.Collections;
    
    public class BundleTextPrefab : MonoBehaviour {
        public UITexture tex;
        public UITexture tex1;
    
        Test tt;
        // Use this for initialization
        void Start () {
            tt = GameObject.Find("UI Root").gameObject.GetComponent<Test>();
            AssetBundle bundle =  tt.DownBundle("");
            if (bundle == null) Debug.Log("bundle == null");
            tex.mainTexture = bundle.LoadAsset("icon") as Texture2D;
        }
    
        // Update is called once per frame
        void Update () {
            if (Input.GetKeyDown(KeyCode.Y)) {
                tt = GameObject.Find("UI Root").gameObject.GetComponent<Test>();
                AssetBundle bundle = tt.DownBundle("");
                if (bundle == null) Debug.Log("bundle == null");
                tex1.mainTexture = bundle.LoadAsset("icon") as Texture2D;
            }
            if (Input.GetKeyDown(KeyCode.T)) {
                tt.Removebundle();
            }
        }
    }
  • 我刚刚 研究Assetbundle  不是很了解   这里只是想做一下记录  上面的代码写的很简陋,是临时做实验写的,以后会慢慢完善,我是打算写出一个游戏的底层框架,包括UI、和异步加载!加油!!
时间: 2024-10-06 16:11:20

Unity5 AssetBundle 打包和下载的相关文章

Unity5 AssetBundle 打包以及加载

using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEditor; using System.IO; public class BuildAssetBundle : Editor { //需要打包的路径,根据项目具体需求自己定 private static string assetPath = "AllAssets"; //导出包路径 private stat

Unity5 Assetbundle简单使用 及 打包Material文件超大的问题

因为项目中要用到ULUA,而ULUA的Demo 中用到的是 Unity5的Assetbundle 打包方式,所以还是学习下 5.0 版本的Assetbundle 打包方式. 简单的来说,Unity5中新添加的 AB 打包,和我们平时使用的方式一样,原理就是 为每个文件创建一个依赖文件,然后汇总到一个总的依赖文件中,在游戏最开始运行的时候需要加载这个 总的依赖文件,然后加载 Assetbundle的时候,从中获取到依赖关系来加载依赖. Unity5的打包Assetbundle API使用起来很方便

Unity5.x版本AssetBundle打包研究

Unity5的AssetBundle打包机制和以前版本不太一样.简单的说就是,只要给你要打包的资源设置一个AssetBundleName ,Unity自身会对这些设置了名字的资源进行打包,如果一个资源依赖了另一个资源.Unity自己会处理依赖关系,AssetBundleManifest文件就保存着这些资源的依赖关系.比如一个UI面板.Prefab,依赖了一个图集Atlas,一个字体文件做个测试:只给UI面板3.prefab设置AssetBundleName.打出包来看,别看只有371KB,那是因

Unity5 AssetBundle系列——基本流程

Unity5的AssetBundle修改比较大,所以第一条建议是:忘掉以前的用法,重新来!要知道,Unity5已经没办法加载2.x 3.x的bundle包了…体会一下Unity5 AssetBundle的优势: Cube引用Material,给Cube和Material设置不同的assetBundleName,分开打包,两个包各自只包含自己,各自独立.如需修改Material,只需要重打包Material即可. 对于4.x版本,要么Cube包中会包含这个Material,导致需要重打整个Cube

[cb] Assetbundle打包(一)

Unity的Assetbundle是Unity Pro提供的功能. 理解:Asset 资源,资产:Bundle :包,一批,捆:字面上的意思,就是把资源打包. 在项目中的实际应用:Art工程,Prefab打包成AssetBundle到Produect目录,Client工程读取AssetBundle; 下面这张图是Art工程 放在Product目录下的Prefab都会打包成AssetBundle 打包AssetBundle到Product目录下[Assetbundle有运行平台之分] Client

Unity AssetBundle打包与资源更新

Unity的AssetBundle打包是一件让人头疼的事情,当我接手这项工作时,我以为最多只用两个周就可以把整个打包和资源热更新的流程搞定,结果还是花了一个月,期间踩坑无数,总结出来希望能够节约别人的时间. (一)你的游戏项目是什么类型的? 在开始写打包的Editor脚本之前,你最好先详细考察一下你们的游戏项目是什么类型?是端游,手游还是页游?因为这三者涉及到bundle包的资源管理策略截然不同,如果你们是跨平台发布,那我建议你最好用宏来切换管理策略. 我先分享一下我曾经接手过打包工作的两个项目

Unity3d 5.x AssetBundle打包与加载

1.AssetBundle打包 unity 5.x版本AssetBundle打包,只需要设置好AssetBundle的名称后,unity会自动将其打包,无需处理其他,唯独需要做的是设置好个AssetBundle的名称. 注意:AssetBunlde的名称只能设置小写字母,即使你写成大写也会被自动转置成大写字母,而且名称中支持"/",如:"AssetBundles/cube.unity3d",.unity3d的后缀是自己设置的,可以不设置 代码: using Unit

Assetbundle 打包加载及服务器加载等(采用unity3d5.0后的新版)

Assetbundle为资源包不是资源 打包1:通过脚本指定打包 AssetBundleBuild ab = new AssetBundleBuild { assetBundleName = PlayerSettings.bundleVersion + "@" + "zhao",//资源包assets的名字 assetNames = new string[1],  //包里的每个资源的名字 }; string outputPath = Path.Combine(Ut

AssetBundle打包优化解决方案

第一阶段:AssetBundle出一套解决方案 1.解决现在同一个资源打2个bundle的冗余问题 2.测试验证节省资源的比率是多少 问题拆分 一.bundle重复 问  题  :相同资源拆分问题? 解决方案:1.制作场景时将相同部分分开 制作方法:将每个场景相同部分放到同一个目录,不同部分保留在场景中 打包方法:a.打成独立的bundle,不同部分放到每个场景中打成bundle b.用xml记录下每个场景中公共部分的transform,bundle名称.资源名称.父节点信息 优    点:打包