Files
Gen_Hack-and-Slash-Roguelit…/Client/Assets/Scripts/Managers/PackagesImageManager.cs
2025-07-17 15:42:24 +08:00

87 lines
2.9 KiB
C#

using System.Collections.Generic;
using System.IO;
using Data;
using UnityEngine;
namespace Managers
{
public class PackagesImageManager : Utils.Singleton<PackagesImageManager>
{
public Dictionary<string, Texture2D> packagesImages = new();
public Dictionary<string, Sprite> sprites = new();
public void Init()
{
if (packagesImages.Count > 0)
return;
var imageDef = Managers.DefineManager.Instance.QueryDefinesByType<ImageDef>();
foreach (var ima in imageDef)
{
if (ima.path == null)
continue;
var pack = Managers.DefineManager.Instance.GetDefinePackage(ima);
var path = Path.Combine(pack.packRootPath, ima.path);
var texture = Configs.ConfigProcessor.LoadTextureByIO(path);
if (texture == null)
continue;
packagesImages.Add(ima.name, texture);
SplitTextureIntoSprites(ima.name, texture, ima.hCount, ima.wCount, ima.pixelsPerUnit);
}
}
void SplitTextureIntoSprites(string name, Texture2D texture, int rows, int cols, int pixelsPerUnit)
{
if (texture == null || rows <= 0 || cols <= 0)
{
Debug.LogError("Invalid parameters for splitting texture.");
return;
}
var textureWidth = texture.width;
var textureHeight = texture.height;
var tileWidth = textureWidth / cols;
var tileHeight = textureHeight / rows;
// 确保纹理可以被整除
if (tileWidth * cols != textureWidth || tileHeight * rows != textureHeight)
{
Debug.LogError("Texture dimensions are not divisible by the specified rows and columns.");
return;
}
// 遍历每一行和每一列
for (var row = 0; row < rows; row++)
{
for (var col = 0; col < cols; col++)
{
// 计算当前小块的矩形区域
var spriteRect = new Rect(col * tileWidth, row * tileHeight, tileWidth, tileHeight);
// 创建Sprite
var sprite = Sprite.Create(texture, (Rect)spriteRect, new Vector2(0.5f, 0.5f), pixelsPerUnit);
var index = row * cols + col;
sprites[name + $"_{index}"] = sprite;
}
}
}
public void Reload()
{
packagesImages.Clear();
Init();
}
public Sprite GetSprite(string name)
{
return sprites.GetValueOrDefault(name, null);
}
public Sprite GetSprite(string name, int index)
{
name += $"_{index}";
return GetSprite(name);
}
}
}