Files
AIC-Project/Client/Assets/Script/xmain/MiniGame/MiniGameAssetLoader.cs
T
2026-07-10 10:24:29 +08:00

58 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XWorld.Framework;
namespace XGame.MiniGame
{
// IAssetLoader over 已下载的小游戏资源 ABmanifest.Assets);首次 Load 时开全部包并缓存,退出统一卸载
public sealed class MiniGameAssetLoader : IAssetLoader
{
private readonly string _localDir;
private readonly List<string> _abNames;
private readonly List<AssetBundle> _opened = new List<AssetBundle>();
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<object> 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);
}
}
}
}