(client) feat:添加瓦片动态定义和资源动态加载
This commit is contained in:
76
Client/Assets/Scripts/Managers/PackagesImageManager.cs
Normal file
76
Client/Assets/Scripts/Managers/PackagesImageManager.cs
Normal file
@ -0,0 +1,76 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user