using System.Collections;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using UnityEngine;
///
/// UI帧动画管理器 - 负责帧动画资源的加载和管理
///
public class UIFrameMgr {
private static UIFrameMgr _inst = null;
private static readonly object _lock = new object();
public static UIFrameMgr Inst {
get {
if (_inst == null) {
lock (_lock) {
if (_inst == null) {
_inst = new UIFrameMgr();
}
}
}
return _inst;
}
}
// 帧动画资源缓存
private Dictionary> allFrameDic = new Dictionary>();
// 是否已初始化
private bool isInitialized = false;
public UIFrameMgr()
{
Init();
}
///
/// 初始化管理器
///
public void Init()
{
if (isInitialized)
return;
allFrameDic.Clear();
isInitialized = true;
}
///
/// 加载指定帧动画资源
///
private void LoadFrameSprites(FrameAnimationConfig cfg)
{
if (allFrameDic.ContainsKey(cfg.name))
return;
List uniTasks = new List();
List spriteList = new List(new Sprite[cfg.frameCnt]);
for (int i = 1; i <= cfg.frameCnt; i++)
{
int index = i;
string spritePath = "Sprite/" + cfg.folder;
string spriteName = StringUtility.Concat(cfg.name, "_", i.ToString());
var task = ResManager.Instance.LoadAssetAsync(spritePath, spriteName).ContinueWith(sprite =>
{
if (sprite != null)
{
spriteList[index - 1] = sprite;
}
else
{
Debug.LogError($"加载帧动画资源失败: {spritePath}/{spriteName}");
}
});
uniTasks.Add(task);
}
UniTask.WhenAll(uniTasks).ContinueWith(() =>
{
if (this == null) // 检查管理器是否已被销毁
return;
if (spriteList.Count > 0)
{
allFrameDic.Add(cfg.name, spriteList);
}
}).Forget();
}
///
/// 获取帧动画资源
///
public List GetDynamicImage(string key)
{
// 按需加载资源
if (!allFrameDic.ContainsKey(key))
{
LoadFrameSprites(FrameAnimationConfig.Get(key));
}
if (allFrameDic.TryGetValue(key, out var list))
{
return list;
}
return null;
}
///
/// 检查是否包含指定帧动画
///
public bool ContainsDynamicImage(string key)
{
return FrameAnimationConfig.HasKey(key);
}
///
/// 预加载指定帧动画
///
public void PreloadDynamicImage(string key)
{
if (!allFrameDic.ContainsKey(key))
{
LoadFrameSprites(FrameAnimationConfig.Get(key));
}
}
}