×

用AssetBundle打包整个目录的资源并调用

Kalet Kalet 发表于2025-04-15 20:26:57 浏览81 评论0

抢沙发发表评论

一、打包整个目录资源

  1. 设置AssetBundle名称

    • 使用编辑器脚本批量设置目录下资源的AssetBundle属性,通过遍历目录文件实现自动化‌58

      [MenuItem("Tools/Set Directory Bundle Name")]
      static void SetBundleName()
      {
          string dirPath = "Assets/Resources/Weapons"; // 目标目录路径
          var assets = AssetDatabase.FindAssets("", new[] { dirPath });
          foreach (var guid in assets) {
              string path = AssetDatabase.GUIDToAssetPath(guid);
              AssetImporter.GetAtPath(path).assetBundleName = "weapons_bundle";
          }
      }
  2. 执行打包操作

    • Editor目录下创建打包脚本,使用BuildPipeline.BuildAssetBundles生成Bundle‌25

      [MenuItem("Tools/Build AssetBundles")]
      static void BuildBundles()
      {
          string outputPath = Path.Combine(Application.streamingAssetsPath, "AssetBundles");
          BuildPipeline.BuildAssetBundles(
              outputPath, 
              BuildAssetBundleOptions.ChunkBasedCompression, 
              BuildTarget.StandaloneWindows
          );
      }
  3. 生成依赖关系

    • 打包完成后自动生成主包AssetBundles.manifest,记录所有Bundle的依赖链‌13


二、调用加载流程

  1. 加载AssetBundle文件

    • 本地加载‌:使用LoadFromFile直接读取StreamingAssets目录下的Bundle‌58

      AssetBundle bundle = AssetBundle.LoadFromFile(
          Path.Combine(Application.streamingAssetsPath, "AssetBundles/weapons_bundle")
      );
    • 远程加载‌:通过UnityWebRequest下载并缓存(支持热更新)‌58

      IEnumerator LoadFromWeb()
      {
          string url = "http://cdn.example.com/bundles/weapons_bundle";
          UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url);
          yield return request.SendWebRequest();
          AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
      }
  2. 加载具体资源

    • 同步加载‌:通过资源名称获取预制体或纹理‌58

      GameObject swordPrefab = bundle.LoadAsset<GameObject>("Sword_01");
      Instantiate(swordPrefab);
    • 异步加载‌:优化性能的分帧加载方式‌17

      IEnumerator LoadAsync()
      {
          AssetBundleRequest request = bundle.LoadAssetAsync<Texture>("Bow_Texture");
          yield return request;
          GetComponent<Renderer>().material.mainTexture = request.asset as Texture;
      }

三、关键注意事项

  1. 依赖加载

    • 通过主包AssetBundleManifest获取依赖列表,需先加载依赖Bundle‌13

      AssetBundle mainBundle = AssetBundle.LoadFromFile("AssetBundles/AssetBundles");
      AssetBundleManifest manifest = mainBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
      string[] deps = manifest.GetAllDependencies("weapons_bundle");
  2. 内存管理

    • 卸载时调用AssetBundle.Unload(true)释放资源内存,避免泄漏‌58

  3. 平台兼容性

    • 不同平台需单独构建Bundle(如Android与iOS不兼容)‌25


群贤毕至

访客