using Cysharp.Threading.Tasks;
|
using UnityEngine;
|
using UnityEngine.U2D;
|
using ProjSG.Resource;
|
|
/// <summary>
|
/// 注册 SpriteAtlasManager.atlasRequested 回调,
|
/// 当 Unity 运行时需要 SpriteAtlas (V2) 时通过 YooAsset 异步加载图集。
|
///
|
/// 根本原因:项目使用 63+ 个 SpriteAtlas V2 (.spriteatlasv2) 文件,
|
/// Prefab 中静态引用的 Sprite 在 AssetBundle 运行时需要通过此回调
|
/// 加载对应的 SpriteAtlas 才能正确显示。
|
/// 编辑器下 Unity 自动处理,但构建后(尤其 WebGL)必须手动处理。
|
/// </summary>
|
public static class SpriteAtlasHandler
|
{
|
private static bool _registered;
|
|
/// <summary>
|
/// 注册 atlasRequested 回调。应在 YooAsset 初始化完成后、UI 加载前调用。
|
/// </summary>
|
public static void Register()
|
{
|
if (_registered) return;
|
_registered = true;
|
|
SpriteAtlasManager.atlasRequested += OnAtlasRequested;
|
Debug.Log("[SpriteAtlasHandler] atlasRequested callback registered.");
|
}
|
|
private static void OnAtlasRequested(string tag, System.Action<SpriteAtlas> callback)
|
{
|
Debug.Log($"[SpriteAtlasHandler] Atlas requested: tag='{tag}'");
|
LoadAtlasAsync(tag, callback).Forget();
|
}
|
|
private static async UniTaskVoid LoadAtlasAsync(string tag, System.Action<SpriteAtlas> callback)
|
{
|
// 主目录: Assets/ResourcesOut/Sprite/{tag}.spriteatlasv2 (UI 包)
|
string location = $"Assets/ResourcesOut/Sprite/{tag}.spriteatlasv2";
|
try
|
{
|
var atlas = await YooAssetService.Instance.LoadAssetAsync<SpriteAtlas>(location);
|
if (atlas != null)
|
{
|
Debug.Log($"[SpriteAtlasHandler] Loaded atlas '{tag}' from '{location}'");
|
callback(atlas);
|
return;
|
}
|
}
|
catch (System.Exception ex)
|
{
|
Debug.LogWarning($"[SpriteAtlasHandler] Failed to load atlas from '{location}': {ex.Message}");
|
}
|
|
// 回退: Assets/ResourcesOut/BuiltIn/Sprites/{tag}.spriteatlasv2 (Builtin 包)
|
string builtinLocation = $"Assets/ResourcesOut/BuiltIn/Sprites/{tag}.spriteatlasv2";
|
try
|
{
|
var atlas = await YooAssetService.Instance.LoadAssetAsync<SpriteAtlas>(builtinLocation);
|
if (atlas != null)
|
{
|
Debug.Log($"[SpriteAtlasHandler] Loaded atlas '{tag}' from '{builtinLocation}'");
|
callback(atlas);
|
return;
|
}
|
}
|
catch (System.Exception ex)
|
{
|
Debug.LogWarning($"[SpriteAtlasHandler] Failed to load atlas from '{builtinLocation}': {ex.Message}");
|
}
|
|
Debug.LogError($"[SpriteAtlasHandler] Could not load SpriteAtlas for tag '{tag}'. " +
|
$"Searched: '{location}', '{builtinLocation}'");
|
}
|
}
|