Unity AssetsBundle包配置加载

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 // 根据目标平台调整
     );
 }
  1. 设置资源标签:在Unity编辑器中,选中需要打包的资源,在Inspector窗口底部设置AssetBundle名称。

  2. 构建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改成不压缩类型才能加载,否则会出现丢失问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值