1、创建AssetsBundle包
[MenuItem("AssetBundles/Build AssetBundles")] //特性
//该脚本需要放在Editor下
static void BuildBundles()
{
string outputPath = Path.Combine(Application.streamingAssetsPath, "AssetBundles");
if (!Directory.Exists(outputPath))
{
Directory.CreateDirectory(outputPath);
}
BuildPipeline.BuildAssetBundles(
outputPath,
BuildAssetBundleOptions.None,
BuildTarget.StandaloneWindows // 根据目标平台调整
);
}
-
设置资源标签:在Unity编辑器中,选中需要打包的资源,在Inspector窗口底部设置AssetBundle名称。
-
构建AB包:通过脚本调用构建方法生成AB包文件。
2、加载AssetsBundle包并实例化模型资源
public string AssetsBundleName = "modelbundle";//Inspector面板assetsbundle包设置的名称(包名)
public string assetName;//包内资源名(通常为预制体的名称)
IEnumerator Start()
{
// 获取AB包路径
string path = Path.Combine(Application.streamingAssetsPath, "AssetBundles", AssetsBundleName);
// 异步加载AB包
var bundleLoadRequest = AssetBundle.LoadFromFileAsync(path);
yield return bundleLoadRequest;
AssetBundle bundle = bundleLoadRequest.assetBundle;
if (bundle == null)
{
Debug.LogError("Failed to load AssetBundle!");
yield break;
}
// 异步加载模型
var assetLoadRequest = bundle.LoadAssetAsync<GameObject>(assetName);
yield return assetLoadRequest;
GameObject model = assetLoadRequest.asset as GameObject;
if (model != null)
{
Instantiate(model, transform.position, Quaternion.identity);
}
// 卸载AB包(false表示保留实例化资源)
bundle.Unload(false);
}
3、从远程服务器加载AssetBundle包
使用UnityWebRequest下载远程包:
IEnumerator LoadFromWeb()
{
string url = "http://your-server.com/AssetBundles/characters";
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url);
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Download failed: " + request.error);
}
else
{
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
// 加载资源并实例化
}
}
4、卸载AssetBundle包与资源管理
-
卸载单个AB包:
bundle.Unload(false);
(保留已实例化的资源)。 -
卸载所有未使用的AB包:
AssetBundle.UnloadAllAssetBundles(false);
-
强制卸载所有资源:
Resources.UnloadUnusedAssets();
5、安卓端加载 AssetBundle包注意事项
1.路径问题:streamingAssetsPath路径在安卓中是"jar:file://" + Application.dataPath + "!/assets",所以加载时路径要修改,(注意:File.ReadAllText 或者 File.Exists Directory.Exists这类对文件的操作打包成安卓是不可用的 )
2.使用ab包加载视频要注意:BuildAssetBundleOptions.UncompressedAssetBundle改成不压缩类型才能加载,否则会出现丢失问题