unity AssetBundle打包以及加载
unity AssetBundle打包
设置资源
- 选中unity资源类文件,如AudioClip,Texture,material,Prefab等
- 设置AssetBundle包
在细节面板(Inspector)中下方打开预览界面,会出现一行AssetBundle,在其中设置(可以设置两个层级)
按上述方法对想要打包的文件进行配置
打包
目前Unity并没有给出自带的打包按钮,只能通过Editor扩展代码,或是下载别人写好的扩展
我采用的是自己写Editor扩展。Editor扩展一定要放在Editor目录下
using System.IO;
using UnityEditor;
public class M_AssetBundleExtend
{
// 该标签在UnityEditor命名空间下,需要引入,字符串参数指
// 定的是路径,编译后会在Unity上方工具栏位在我们指定的路径下
// 生成一个扩展按钮,点击就会执行下方的CreatAssetBundle()方法
// 这也是为什么该方法要是静态.
[MenuItem("M_Asset/CreatAssetBundle")]
// 这里的方法一定要是静态
public static void CreatAssetBundle() {
//生成字符串的路径,该路径根目录在unity工程下(与Asset同级)
string path = "AssetBundle";
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
//打包
BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
}
}
在工具栏找到我们刚才写的扩展,点击,打包完成.
AB包的简单操作
加载ab包,并获取资源
using UnityEngine;
public class LoadAssetBunld : MonoBehaviour
{
void Start()
{
// 从项目目录文件下加载ab包(这里的AssetBundle和Asset在同一级).
AssetBundle bundle = AssetBundle.LoadFromFile("AssetBundle/audio");
// 从ab包加载需要使用的资源并设置.
AudioClip clip = bundle.LoadAsset<AudioClip>("audio_SeaWav");
this.GetComponent<AudioSource>().clip = clip;
this.GetComponent<AudioSource>().Play();
}
}
加载ab包,并获取ab包依赖
using UnityEngine;
public class GetAssetBundleManifest : MonoBehaviour
{
private void Start()
{
// 加载ab包,但这个包并不是我们在unity设置的ab包,而是打包ab时unity自动在
// 打包路径下创建的和文件夹同名的ab包,他包含了所有包的依赖关系.
AssetBundle bundle = AssetBundle.LoadFromFile("AssetBundle/AssetBundle");
// 从ab包中加载AssetBundleManifest文件,包含了ab包的引用信息
AssetBundleManifest bundleManifest = bundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
// 循环打印引用.
foreach (var item in bundleManifest.GetAllDependencies("m_assetbundle"))
{
Debug.Log(item);
}
}
}