打包资源AssetBunldes

作者:追风剑情 发布于:2014-7-13 14:57 分类:Unity3d

原文链接 http://blog.csdn.net/dingxiaowei2013/article/details/17439887


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

public class AssetBunldesEditor : Editor {

	//打包单个
	[MenuItem("Custom/Create AssetBunldes")]
	static void CreateAssetBunldes ()
	{
		//获取在Project视图中选择的所有游戏对象
		Object[] SelectedAsset = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);
		
                  string streamingPath = Application.dataPath + "/StreamingAssets";
                  if (!Directory.Exists(streamingPath))
                      Directory.CreateDirectory(streamingPath);

		//遍历所有的游戏对象
		foreach (Object obj in SelectedAsset) 
		{
			//本地测试:建议最后将Assetbundle放在StreamingAssets文件夹下,如果没有就创建一个,因为移动平台下只能读取这个路径
			//StreamingAssets是只读路径,不能写入
			//服务器下载:就不需要放在这里,服务器上客户端用www类进行下载。
			string targetPath = Application.dataPath + "/StreamingAssets/" + obj.name + ".assetbundle";
			if (BuildPipeline.BuildAssetBundle (obj, null, targetPath, BuildAssetBundleOptions.CollectDependencies)) {
				Debug.Log(obj.name +"资源打包成功");
			} 
			else 
			{
				Debug.Log(obj.name +"资源打包失败");
			}
		}
		//刷新编辑器
		AssetDatabase.Refresh ();	
	}

	//多个资源打成一个包
	[MenuItem("Custom/Create AssetBunldes ALL")]
	static void CreateAssetBunldesALL ()
	{
		Caching.CleanCache ();
		string Path = Application.dataPath + "/StreamingAssets/ALL.assetbundle";
		
		Object[] SelectedAsset = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);
		
		foreach (Object obj in SelectedAsset) 
		{
			Debug.Log ("Create AssetBunldes name :" + obj);
		}
		
		//这里注意第二个参数就行
		if (BuildPipeline.BuildAssetBundle (null, SelectedAsset, Path, BuildAssetBundleOptions.CollectDependencies)) {
			AssetDatabase.Refresh ();
		} else {
			
		}
	}
}
手动新建一个目录Assets/StreamingAssets 并把AssetBunldesEditor.cs放在Assets/Editor/下面


//打包资源时通常使用下面项
//包含所有依赖关系 | 强制包括整个资源 | 确保生成唯一ID(打包依赖时会有用)
BuildAssetBundleOptions options = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.DeterministicAssetBundle;


示例:在编辑器中导出模型与加载模型


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

/// <summary>
/// 资源工具
/// </summary>
public class AssetToolEditor
{
    [MenuItem("Assets/Tool/导出选中模型")]
    public static void MenuExportModel()
    {
        Object obj = Selection.activeObject;
        string asset_path = AssetDatabase.GetAssetPath(obj);
        string export_folder = Application.streamingAssetsPath + "/model";
        if (!Directory.Exists(export_folder))
        {
            Directory.CreateDirectory(export_folder);
            AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
        }
        Debug.Log(export_folder);

        string[] assetNames = AssetDatabase.GetDependencies(asset_path);
        BuildAssetBundleOptions options = BuildAssetBundleOptions.ChunkBasedCompression;
        AssetBundleBuild abb = new AssetBundleBuild();
        abb.assetBundleName = obj.name;
        abb.assetBundleVariant = "model";
        abb.assetNames = assetNames;
        BuildPipeline.BuildAssetBundles(export_folder, new AssetBundleBuild[] { abb }, options, EditorUserBuildSettings.activeBuildTarget);
        AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);

        //删除生成的manifest文件
        export_folder = export_folder.Substring(export_folder.LastIndexOf("/Assets/") + 1);
        AssetDatabase.DeleteAsset(string.Format("{0}/{1}.{2}.manifest", export_folder, abb.assetBundleName.ToLower(), abb.assetBundleVariant));
        string folder_name = export_folder.Substring(export_folder.LastIndexOf("/") + 1);
        AssetDatabase.DeleteAsset(string.Format("{0}/{1}.manifest", export_folder, folder_name));
        AssetDatabase.DeleteAsset(string.Format("{0}/{1}", export_folder, folder_name));

        AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
    }

    [MenuItem("Assets/Tool/加载导出模型")]
    public static void LoadExportModel()
    {
        Object obj = Selection.activeObject;
        string asset_path = AssetDatabase.GetAssetPath(obj);
        string url = string.Format("{0}/{1}", Application.dataPath.Replace("/Assets", ""), asset_path);
        Debug.Log(url);
        //释放掉之前加载的
        AssetBundle.UnloadAllAssetBundles(true);
        AssetBundle ab = AssetBundle.LoadFromFile(url);
        Debug.Log(ab);
        if (ab == null)
        {
            Debug.LogErrorFormat("ab=null");
            return;
        }

        GameObject model = null;
        Object[] objs = ab.LoadAllAssets();
        for (int i = 0; i < objs.Length; i++)
        {
            if (objs[i] is GameObject)
            {
                if (objs[i].name.ToLower() == obj.name.ToLower())
                {
                    model = objs[i] as GameObject;
                }
            }
            //Debug.Log(objs[i]);
        }

        if (model == null)
            return;
        GameObject.Instantiate(model);
    }
}


标签: AssetBunldes

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号