yyl
2026-03-26 1ab047b5fdd933c38ba0519ec2e83a44512ea8d7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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}'");
    }
}