一、设置bundle名称
相同名称会打包到一个AssetBundle中,后缀可有可无,如果添加后缀,加载时也需要加上后缀
1.1代码批量设置名称 首先将需要打包的资源放到同一个大的文件夹,meta文件不打包
var path = "Assets/Data/";
foreach (var filePath in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories))
{
if (filePath.EndsWith(".meta")) continue;
var importer = AssetImporter.GetAtPath(filePath);
if (importer == null)
{
LogUtility.Error("Not found: " + filePath);
continue;
}
//FileInfo fileInfo = new FileInfo(filePath);
//importer.assetBundleName = fileInfo.Name + ".unity3d";
importer.assetBundleName = filePath.Replace("Assets/Data/", "").ToLower() + ".unity3d";
}
二、 打包和加载 AssetBundle
资源描述::
Cube 的Assetbundle名称为 test
Cube_1 的Assetbundle名称为 cube_1
Sphere_1的 Assetbundle名称为 cube_2
图片4和New Material 全部打包在test中
当有多个prefab依赖一个资源时,将依赖资源单独打包,加载时,也需要先加载依赖资源,具体打包规范
如果不将依赖公用的资源单独打包,它就会存在与多个AssetBundle中,造成资源浪费,包体变大
2.1 打包
脚本放到Editor文件夹
BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
三个参数: 路径,压缩方式,目标平台
[MenuItem("Assets/BuildAssetBundles")]
static void CreateAndroidAssertBundle()
{
string assetBundleDirectory = "Assets/AssetBundles";
if (!Directory.Exists(assetBundleDirectory))
{
Directory.CreateDirectory(assetBundleDirectory);
}
BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
}
2.2 加载bundle
2.2.1.本地加载
AssetBundle ab = AssetBundle.LoadFromFile("assetBundlePath");
参数为AssetBundle的路径,如果设置后缀,加载时加上后缀 比如AssetBundle.LoadFromFile("Assets/AssetBundles/Android/test.unity3d");
预设 cube、图片4和New Material 都在名称为text的assetbundle中
private void Load_1()
{
AssetBundle ab = AssetBundle.LoadFromFile("Assets/AssetBundles/test");
if (ab != null)
{
Instantiate(ab.LoadAsset<GameObject>("Cube"));
Sprite tex = ab.LoadAsset<Sprite>("4");
renderer.sprite = tex;
}
}
加载有依赖项的AssetBundle
预设Cube1打包在名称为cube1的assetbundle中,它依赖assetbundle名为test中的图片4和New Material
当打包bundle时,会生成一个bundle所在文件夹名称的bundle,记录文件夹下所有bundle的信息,依赖关系
AssetBundle ab = AssetBundle.LoadFromFile("Assets/AssetBundles/assetBundles");
//"AssetBundleManifest"为固定写法
AssetBundleManifest manifest = ab.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
//获取所有依赖
string[] dependencie = manifest.GetAllDependencies("cube1");
foreach (var item in dependencie)
{
AssetBundle.LoadFromFile(Path.Combine("Assets/AssetBundles", item));
}
AssetBundle sphereAssetBundle = AssetBundle.LoadFromFile("Assets/AssetBundles/cube1");
Instantiate(sphereAssetBundle.LoadAsset<GameObject>("Cube_1"));