u3d 打包 BuildAssetBundle

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
using System;
public class CreateAssetBunldes
{
[MenuItem("BundleExporter/package/打包配置")]
private static void PackConfig()
{
if (!EditorUtility.DisplayDialog("打包","需要打包Config文件吗?","yes","no")) {//对话框
return;
}
Package("Assets/Config");//config文件的路径
}
static void Package(string path)
{
string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);//得到config文件夹下面的所有带.的文件
if (files.Length > 0)
{
UnityEngine.Object[] select = new UnityEngine.Object[files.Length];
int idx = 0;
foreach(string file in files)
{
UnityEngine.Object go = AssetDatabase.LoadAssetAtPath(file ,typeof(UnityEngine.Object));
if (go != null)
{
go.name = go.name.Trim();
select[idx] = go;
idx++;
}
}
Package(select);
}
}

static void Package(UnityEngine.Object[] objects)
{
try
{
if (objects.Length < 0) return;
string path = AssetDatabase.GetAssetPath(objects[0]);
if (string.IsNullOrEmpty(path)) return;
path = path.Substring(0, LastSlash(path));
UnityEngine.Object parDir = AssetDatabase.LoadAssetAtPath(path, typeof(UnityEngine.Object));//加载文件
if (parDir==null) {
Debug.Log("包裹名不存在,必须是一个目录!");
return;
}
int index = LastSlash(path) + 1;
string pkgName = path.Substring(index, path.Length - index);
PackCurrentSelect(pkgName, objects);
}
catch(Exception ex)
{

}
}
static void PackCurrentSelect(string pkgName, UnityEngine.Object[] objects)
{
BuildTarget target = BuildTarget.StandaloneWindows;
string path = string.Format("{0}_S.unity3d", pkgName);
//开始打包
#if UNITY_ANDROID
target = BuildTarget.Android;
//path = string.Format("{0}_A_{1}.unity3d", pkgName, version);
path = string.Format("{0}_A.unity3d", pkgName);
#endif
#if UNITY_IPHONE
target = BuildTarget.iOS;
path = string.Format("{0}_I.unity3d", pkgName);
#endif
#if UNITY_WEBPLAYER
target = BuildTarget.WebPlayer;
path = string.Format("{0}_W.unity3d", pkgName);
#endif
#if UNITY_STANDALONE_WIN
target = BuildTarget.StandaloneWindows;
path = string.Format("{0}_S.unity3d", pkgName);
#endif
#if UNITY_FLASH
target = BuildTarget.FlashPlayer;
path = string.Format("{0}_F.unity3d", pkgID);
#endif
string bundlePath = ToLocalBundlePath(path);
if (objects.Length > 0)
{
BuildPipeline.BuildAssetBundle(objects[0], objects, bundlePath, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, target);
}

}

static int LastSlash(string dir)
{
return dir.LastIndexOfAny(new char[] { '/', '\\' });
}

static public string ToLocalBundlePath(string fileName)
{
fileName = fileName.Trim(); //有的文件会有空格
return Application.dataPath + "/StreamingAssets/" + fileName;
}
}

 

 

 

 

posted @ 2017-10-13 15:48  无止境!  阅读(432)  评论(0编辑  收藏  举报