using System; using System.Collections.Generic; using System.IO; using UnityEngine; using XWorld.Framework; namespace XGame.MiniGame { // IAssetLoader over 已下载的小游戏资源 AB(manifest.Assets);首次 Load 时开全部包并缓存,退出统一卸载 public sealed class MiniGameAssetLoader : IAssetLoader { private readonly string _localDir; private readonly List _abNames; private readonly List _opened = new List(); private bool _openedAll; public MiniGameAssetLoader(string localDir, MiniGameManifest manifest) { _localDir = localDir; _abNames = manifest.Assets; } // path: 打包时的资产路径(如 "Assets/MiniGames/RockPaperScissors/res/UI/Prefab/UI_RockPaperScissors.prefab") // 或裸资产名("UI_RockPaperScissors");找不到回调 null。 public void Load(string path, Action onLoaded) { EnsureOpened(); foreach (var ab in _opened) { UnityEngine.Object obj = ab.LoadAsset(path); if (obj == null) obj = ab.LoadAsset(Path.GetFileNameWithoutExtension(path)); if (obj != null) { onLoaded?.Invoke(obj); return; } } Debug.LogError("[MiniGameAssetLoader] 资产未找到: " + path); onLoaded?.Invoke(null); } // 小游戏退出时由 MiniGameHost 调用;true=连已实例化引用的资产一起卸 public void UnloadAll() { foreach (var ab in _opened) if (ab != null) ab.Unload(true); _opened.Clear(); _openedAll = false; } private void EnsureOpened() { if (_openedAll) return; _openedAll = true; foreach (var name in _abNames) { string p = _localDir + name; if (!File.Exists(p)) { Debug.LogError("[MiniGameAssetLoader] 资源 AB 缺失: " + p); continue; } var ab = MiniGamePlatform.LoadAssetBundle(p); if (ab == null) { Debug.LogError("[MiniGameAssetLoader] 资源 AB 打开失败: " + p); continue; } _opened.Add(ab); } } } }