Unity AssetBundle打包
程序员文章站
2022-04-03 15:39:06
...
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.VersionControl;
using UnityEngine;
public class AssetBundleBuilder : Editor
{
/// <summary>
/// 资源打包路径
/// </summary>
private static string m_OutPath = Application.dataPath + "/BundleRes";
/// <summary>
/// 资源输出路径
/// </summary>
private static string m_PutPath = Application.streamingAssetsPath;
[MenuItem("AssetBundle/Build")]
static void BuildAssetBundle()
{
ClearAssetBundlesName();
Pack(m_OutPath);
string outPutPath = Path.Combine(m_PutPath,GetPlatformFolder(EditorUserBuildSettings.activeBuildTarget));
if (!Directory.Exists(outPutPath))
{
Directory.CreateDirectory(outPutPath);
}
BuildPipeline.BuildAssetBundles(outPutPath,BuildAssetBundleOptions.None,EditorUserBuildSettings.activeBuildTarget);
AssetDatabase.Refresh();
Debug.Log("打包完成!!!!!");
}
/// <summary>
/// 清除AssetBundleName
/// </summary>
private static void ClearAssetBundlesName()
{
//获取所有的AssetBundleName
string[] str = AssetDatabase.GetAllAssetBundleNames();
foreach (var names in str)
{
//移除掉BundleName
AssetDatabase.RemoveAssetBundleName(names,true);
}
str = AssetDatabase.GetAllAssetBundleNames();
}
/// <summary>
/// 拿到需要打包的文件
/// </summary>
private static void Pack(string path)
{
DirectoryInfo dire = new DirectoryInfo(path);
FileSystemInfo[] files = dire.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
if(files[i] is DirectoryInfo)
{
Pack(files[i].FullName);
}
else
{
if (!files[i].Name.EndsWith(".meta"))
{
SetAssetBundleName(files[i].FullName);
}
}
}
}
/// <summary>
/// 设置AssetBundleName
/// </summary>
private static void SetAssetBundleName(string source)
{
string _source = Replace(source);
string _assetPath1 = "Assets" + _source.Substring(Application.dataPath.Length);
string _assetPath2 = _source.Substring(Application.dataPath.Length + 1);
AssetImporter assetImporter = AssetImporter.GetAtPath(_assetPath1);
string assetName = _assetPath2.Substring(_assetPath2.IndexOf("/") + 1);
assetName = assetName.Replace(Path.GetExtension(assetName),".unity3d");
assetImporter.assetBundleName = assetName;
}
private static string Replace(string str)
{
return str.Replace(@"\\","/");
}
private static string GetPlatformFolder(BuildTarget target)
{
switch (target)
{
case BuildTarget.Android:
return "Android";
case BuildTarget.iOS:
return "iOS";
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
return "Windows";
case BuildTarget.StandaloneOSXIntel:
case BuildTarget.StandaloneOSXIntel64:
return "OSX";
default:
break;
}
return null;
}
}