记录一下日常使用的几种资源AssetBundle打包和加载方式(5.x),学习过和做过的东西要时常回顾,在博客记录下来其实是个很好的方式,温故而知新。突然哪一天开始不使用某个技术了很容易忘记,原来自己做过这些(- . -)
模型打包AssetBundle资源
static void BuildModel()
{
//选中的模型资源打包成一个.unity3d文件
foreach (var item in Selection.objects)
{
List<AssetBundleBuild> lst = new List<AssetBundleBuild>();
AssetBundleBuild build = new AssetBundleBuild();
build.assetBundleName = item.name + ".unity3d";
build.assetNames = new string[] { AssetDatabase.GetAssetPath(item) };
lst.Add(build);
string path = Application.streamingAssetsPath;//build.assetNames[0].Remove(build.assetNames[0].LastIndexOf("/")); //路径可以自己设置
if (path.Length != 0)
{
BuildPipeline.BuildAssetBundles(path, lst.ToArray(), BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}
}
AssetDatabase.Refresh();
}
音频打包AssetBundle资源
static void BuildAudio()
{
string path = Application.dataPath + "/StreamingAssets/"; //路径自己设置
List<AssetBundleBuild> lst = new List<AssetBundleBuild>();
AssetBundleBuild build = new AssetBundleBuild();
build.assetBundleName = "Audios.unity3d";
List<string> lstpath = new List<string>();
foreach (var item in Selection.objects)
{
lstpath.Add(AssetDatabase.GetAssetPath(item));
}
build.assetNames = lstpath.ToArray();
lst.Add(build);
AssetDatabase.DeleteAsset(path);
if (path.Length != 0)
{
BuildPipeline.BuildAssetBundles(path, lst.ToArray(), BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}
FileInfo fi = new FileInfo(path + build.assetBundleName);
fi.MoveTo(path + build.assetBundleName);
AssetDatabase.Refresh();
}
图片打包AssetBundle资源
static void BuildTexture()
{
string path = Application.dataPath + "/StreamingAssets/"; //路径自己设置
List<AssetBundleBuild> lst = new List<AssetBundleBuild>();
AssetBundleBuild build = new AssetBundleBuild();
build.assetBundleName = "Audios.unity3d";
List<string> lstpath = new List<string>();
foreach (var item in Selection.objects)
{
lstpath.Add(AssetDatabase.GetAssetPath(item));
}
build.assetNames = lstpath.ToArray();
lst.Add(build);
AssetDatabase.DeleteAsset(path);
if (path.Length != 0)
{
BuildPipeline.BuildAssetBundles(path, lst.ToArray(), BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}
FileInfo fi = new FileInfo(path + build.assetBundleName);
fi.MoveTo(path + build.assetBundleName);
AssetDatabase.Refresh();
}
- 主要函数BuildPipeline.BuildAssetBundles
- 重载一:BuildAssetBundles(string outputPath, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform);
- 重载二:BuildAssetBundles(string outputPath, AssetBundleBuild[] builds, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform);
outputPath:输出路径
AssetBundleBuild[]:资源
BuildAssetBundleOptions:资源类型设置(一般设置为None就可以了,如果在webgl使用则选用ChunkBasedCompression方式,此选项采用webgl支持LZ4的压缩方式)
BuildTarget:目标平台,即在什么平台加载使用该资源