yyl
2026-02-11 3f2cd27c5dfb3b450245bf1a37fc1b3414031c7c
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// ============================================================================
// ResourcePreloader.cs — 资源预加载管理器
// Feature: 001-async-resource-loading
// ============================================================================
 
using System;
using System.Collections.Generic;
using UnityEngine;
using Cysharp.Threading.Tasks;
 
namespace ProjSG.Resource
{
    /// <summary>
    /// 资源预加载管理器。
    /// 按场景/流程组织预加载配置,通过 ResourceCacheManager 执行实际缓存。
    /// </summary>
    public class ResourcePreloader : Singleton<ResourcePreloader>, IResourcePreloader
    {
        private readonly Dictionary<string, PreloadConfig> _configs = new Dictionary<string, PreloadConfig>();
        private readonly HashSet<string> _loadedConfigs = new HashSet<string>();
 
        // ====================================================================
        // 预设配置
        // ====================================================================
 
        /// <summary>
        /// 注册默认预加载配置。应在 YooAsset 初始化后调用。
        /// </summary>
        public void RegisterDefaultConfigs()
        {
            // 启动必需资源(常驻)
            RegisterConfig(new PreloadConfig
            {
                ConfigName = "StartupEssential",
                Locations = new[]
                {
                    "Assets/ResourcesOut/Shader",                // Shader 全部
                    "Assets/ResourcesOut/Materials",             // 通用 Material
                    "Assets/ResourcesOut/BuiltIn/Font",          // 常用字体
                    "Assets/ResourcesOut/BuiltIn/UIRoot",        // UIRoot 预制体
                    "Assets/ResourcesOut/BuiltIn/SoundPlayer",   // 音频播放器
                },
                Tags = null,
                IsPermanent = true,
            });
 
            // 战斗场景资源(非常驻,战斗结束后可释放)
            RegisterConfig(new PreloadConfig
            {
                ConfigName = "BattleScene",
                Locations = null,
                Tags = new[] { "tag_battle_spine", "tag_battle_effect", "tag_battle_sound" },
                IsPermanent = false,
            });
        }
 
        // ====================================================================
        // IResourcePreloader 实现
        // ====================================================================
 
        /// <inheritdoc/>
        public void RegisterConfig(PreloadConfig config)
        {
            if (config == null || string.IsNullOrEmpty(config.ConfigName))
            {
                Debug.LogError("ResourcePreloader.RegisterConfig: config or ConfigName is null");
                return;
            }
 
            _configs[config.ConfigName] = config;
        }
 
        /// <inheritdoc/>
        public async UniTask PreloadAsync(string configName, IProgress<float> progress = null)
        {
            if (string.IsNullOrEmpty(configName))
            {
                Debug.LogError("ResourcePreloader.PreloadAsync: configName is null or empty");
                progress?.Report(1f);
                return;
            }
 
            if (!_configs.TryGetValue(configName, out var config))
            {
                Debug.LogWarning($"ResourcePreloader.PreloadAsync: config '{configName}' not found");
                progress?.Report(1f);
                return;
            }
 
            if (_loadedConfigs.Contains(configName))
            {
                progress?.Report(1f);
                return;
            }
 
            var cacheManager = ResourceCacheManager.Instance;
            int totalSteps = 0;
            int completedSteps = 0;
 
            // 计算总步骤
            if (config.Locations != null) totalSteps += config.Locations.Length;
            if (config.Tags != null) totalSteps += config.Tags.Length;
 
            if (totalSteps == 0)
            {
                progress?.Report(1f);
                _loadedConfigs.Add(configName);
                return;
            }
 
            // 加载 Locations
            if (config.Locations != null && config.Locations.Length > 0)
            {
                var locationProgress = new Progress<float>(p =>
                {
                    float locationWeight = (float)config.Locations.Length / totalSteps;
                    progress?.Report(p * locationWeight);
                });
 
                await cacheManager.PreloadAsync(config.Locations, config.IsPermanent, locationProgress);
                completedSteps += config.Locations.Length;
            }
 
            // 按 Tag 加载
            if (config.Tags != null)
            {
                foreach (var tag in config.Tags)
                {
                    await PreloadByTagAsync(tag);
                    completedSteps++;
                    progress?.Report((float)completedSteps / totalSteps);
                }
            }
 
            _loadedConfigs.Add(configName);
            progress?.Report(1f);
        }
 
        /// <inheritdoc/>
        public async UniTask PreloadByTagAsync(string tag, IProgress<float> progress = null)
        {
            if (string.IsNullOrEmpty(tag))
            {
                progress?.Report(1f);
                return;
            }
 
            try
            {
                // 使用 YooAssetService 按标签下载/缓存
                await YooAssetService.Instance.DownloadByTagsAsync(
                    new[] { tag },
                    progress: progress);
 
                progress?.Report(1f);
            }
            catch (Exception e)
            {
                Debug.LogError($"ResourcePreloader.PreloadByTagAsync failed for tag '{tag}': {e.Message}");
                progress?.Report(1f);
            }
        }
 
        /// <inheritdoc/>
        public void UnloadConfig(string configName)
        {
            if (string.IsNullOrEmpty(configName)) return;
 
            if (!_configs.TryGetValue(configName, out var config)) return;
 
            // 常驻配置不卸载
            if (config.IsPermanent)
            {
                Debug.LogWarning($"ResourcePreloader.UnloadConfig: config '{configName}' is permanent, skipping unload");
                return;
            }
 
            if (config.Locations != null)
            {
                var cacheManager = ResourceCacheManager.Instance;
                foreach (var loc in config.Locations)
                {
                    cacheManager.Release(loc);
                }
            }
 
            _loadedConfigs.Remove(configName);
        }
 
        /// <inheritdoc/>
        public bool IsConfigLoaded(string configName)
        {
            return _loadedConfigs.Contains(configName);
        }
    }
}