AssetBundle简称AB包,特定平台的资产压缩包(包括模型、贴图、预设体、音效、材质球等资产)
作用:Resources下的资源只读且打包后不可修改,而AB包存储位置自定,后期可以动态更新;AB包压缩后节省空间;可以进行资源热更新和脚本热更新
首先创建一个Editor文件夹(会创建Tools的一个菜单项)
里面建一个test.cs测试文件(用ab包必须将脚本建在Editor下)
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using System.IO;
using UnityEngine;
public class test : Editor
{
[MenuItem("编辑器/编辑")]
public static void run()
{
Debug.Log("编辑测试");
string path = Application.streamingAssetsPath;//Assets/StreamingAsset文件
if (!Directory.Exists(path))//判断路径下是否有文件夹
{
Directory.CreateDirectory(path);
}
//资源打包为AB包
BuildPipeline.BuildAssetBundles(path,BuildAssetBundleOptions.ChunkBasedCompression,BuildTarget.StandaloneWindows64);
}
}
然后在别的地方创建一个新的脚本(本地加载克隆)
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class ABtest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//解压资源并生成AB包对象
AssetBundle ab = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath,"cube"));//ab包
GameObject go = ab.LoadAsset<GameObject>("cube");//预设的名字
Instantiate(go);
}
}
克隆之前要先创建一个Cube并做成预设,将预设放入Resources中,修改Cube属性里的AeestBundle
将克隆脚本挂载摄像机
运行后就可以看到有立方体克隆出来
AssetBundle打包时会把依赖关系存储在manifest清单文件里,我们也可以通过加载manifest来动态获取依赖关系
Manifest文件
CRC为校验码,通过其检查是否完整
Assets 表示包里包含多少资源
Dependencies 表示包有哪些依赖
注意:在加载这些包之前,也需要加载依赖的包,不然会丢失这部分内容,显示效果不正确