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

343 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;
using Formatting = Newtonsoft.Json.Formatting;
namespace Configs
{
public static class ConfigProcessor
{
// 保存文件的默认文件夹路径
private const string FolderPath = "save";
/// <summary>
/// 初始化文件夹
/// </summary>
static ConfigProcessor()
{
if (!Directory.Exists(FolderPath)) Directory.CreateDirectory(FolderPath);
}
/// <summary>
/// 保存单个类为 JSON 文件
/// </summary>
/// <param name="obj">要保存的类对象</param>
/// <param name="fileName">可选的文件名(不包括扩展名)</param>
public static bool SaveFile<T>(T obj, string fileName = null)
{
try
{
// 如果未提供文件名,则使用类名作为文件名
if (string.IsNullOrEmpty(fileName)) fileName = typeof(T).Name;
// 构建完整的文件路径
var filePath = Path.Combine(FolderPath, fileName + ".json");
// 将对象序列化为 JSON 字符串
var jsonContent = JsonConvert.SerializeObject(obj, Formatting.Indented);
// 写入文件
File.WriteAllText(filePath, jsonContent);
Debug.Log($"Saved file: {filePath}");
return true;
}
catch (Exception ex)
{
Debug.LogError($"Failed to save file: {ex.Message}");
return false;
}
}
/// <summary>
/// 从 JSON 文件读取单个类
/// </summary>
/// <param name="fileName">文件名(不包括扩展名)</param>
public static T LoadFile<T>(string fileName)
{
try
{
// 构建完整的文件路径
var filePath = Path.Combine(FolderPath, fileName + ".json");
// 检查文件是否存在
if (!File.Exists(filePath))
{
Debug.LogError($"File not found: {filePath}");
return default;
}
// 读取文件内容
var jsonContent = File.ReadAllText(filePath);
// 反序列化为指定类型的对象
var obj = JsonConvert.DeserializeObject<T>(jsonContent);
Debug.Log($"Loaded file: {filePath}");
return obj;
}
catch (Exception ex)
{
Debug.LogError($"Failed to load file: {ex.Message}");
return default;
}
}
/// <summary>
/// 打包多个类并保存为一个存档文件
/// </summary>
/// <param name="archiveName">存档文件名(不包括扩展名)</param>
/// <param name="objects">要保存的类对象字典</param>
public static bool SaveArchive(string archiveName, Dictionary<string, object> objects)
{
try
{
// 构建完整的文件路径
var filePath = Path.Combine(FolderPath, archiveName + ".archive.json");
// 将字典中的对象序列化为 JSON
var jsonContent = JsonConvert.SerializeObject(objects, Formatting.Indented);
// 写入文件
File.WriteAllText(filePath, jsonContent);
Debug.Log($"Saved archive: {filePath}");
return true;
}
catch (Exception ex)
{
Debug.LogError($"Failed to save archive: {ex.Message}");
return false;
}
}
/// <summary>
/// 从存档文件中读取多个类
/// </summary>
/// <param name="archiveName">存档文件名(不包括扩展名)</param>
public static Dictionary<string, object> LoadArchive(string archiveName)
{
try
{
// 构建完整的文件路径
var filePath = Path.Combine(FolderPath, archiveName + ".archive.json");
// 检查文件是否存在
if (!File.Exists(filePath))
{
Debug.LogError($"Archive not found: {filePath}");
return null;
}
// 读取文件内容
var jsonContent = File.ReadAllText(filePath);
// 反序列化为字典
var objects = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonContent);
Debug.Log($"Loaded archive: {filePath}");
return objects;
}
catch (Exception ex)
{
Debug.LogError($"Failed to load archive: {ex.Message}");
return null;
}
}
/// <summary>
/// 获取指定路径下的所有xml文件
/// </summary>
/// <param name="paths">文件夹路径</param>
/// <returns></returns>
public static List<string> GetXmlFilePathsFromPaths(string[] paths)
{
var xmlFilePaths = new List<string>();
foreach (var path in paths)
{
try
{
// 检查目录是否存在
if (!Directory.Exists(path))
{
continue;
}
// 获取目录下的所有子文件夹
var subDirectories = Directory.GetDirectories(path);
// 遍历并收集每个子文件夹中的 XML 文件
foreach (var dir in subDirectories)
{
var xmlFiles = Directory.GetFiles(dir, "*.xml", SearchOption.AllDirectories);
xmlFilePaths.AddRange(xmlFiles);
}
}
catch (Exception ex)
{
Debug.LogError($"加载文件时发生错误: {ex.Message}");
}
}
return xmlFilePaths;
}
/// <summary>
/// 从指定路径加载所有 XML 文件并解析为 XDocument 对象。
/// </summary>
/// <param name="paths">文件夹路径数组。</param>
/// <returns>包含所有解析后的 XDocument 对象的列表。</returns>
public static List<XDocument> LoadXmlFromPaths(string[] paths)
{
var xDocuments = new List<XDocument>();
var xmlFilePaths = GetXmlFilePathsFromPaths(paths);
foreach (var filePath in xmlFilePaths)
try
{
var xDoc = XDocument.Load(filePath);
xDocuments.Add(xDoc);
}
catch (Exception ex)
{
Debug.LogError($"加载 XML 文件 {filePath} 时发生错误: {ex.Message}");
}
return xDocuments;
}
/// <summary>
/// 获取指定单个路径下的所有 XML 文件。
/// </summary>
/// <param name="path">文件夹路径。</param>
/// <returns>包含所有 XML 文件路径的列表。</returns>
public static List<string> GetXmlFilePathsFromPath(string path)
{
return GetXmlFilePathsFromPaths(new[] { path });
}
/// <summary>
/// 从指定单个路径加载所有 XML 文件并解析为 XDocument 对象。
/// </summary>
/// <param name="path">文件夹路径。</param>
/// <returns>包含所有解析后的 XDocument 对象的列表。</returns>
public static List<XDocument> LoadXmlFromPath(string path)
{
return LoadXmlFromPaths(new[] { path });
}
/// <summary>
/// 获取文件夹列表中所有直接子文件夹的路径。
/// </summary>
/// <param name="folderPaths">文件夹路径列表。</param>
/// <returns>包含所有子文件夹路径的列表。</returns>
public static List<string> GetSubFolders(List<string> folderPaths)
{
var result = new List<string>();
foreach (var folderPath in folderPaths)
if (Directory.Exists(folderPath))
{
// 获取当前文件夹的直接子文件夹
var subFolders = Directory.GetDirectories(folderPath);
// 将子文件夹路径添加到结果列表中
result.AddRange(subFolders);
}
else
{
Debug.LogWarning($"警告: 文件夹不存在 - {folderPath}");
}
return result;
}
/// <summary>
/// 用于加载指定路径下的所有资源,并返回资源名称和加载好的资源的键值对。
/// </summary>
/// <typeparam name="T">资源类型</typeparam>
/// <param name="path">资源路径(相对于 Resources 文件夹)</param>
/// <returns>字典,键为资源名称,值为加载好的资源</returns>
public static Dictionary<string, T> LoadResources<T>(string path) where T : UnityEngine.Object
{
// 创建一个字典来存储资源名称和加载好的资源
Dictionary<string, T> resourceDict = new Dictionary<string, T>();
// 加载指定路径下的所有资源
T[] resources = Resources.LoadAll<T>(path);
foreach (T resource in resources)
{
if (resource != null)
{
// 获取资源名称并存入字典
string resourceName = resource.name;
resourceDict[resourceName] = resource;
}
}
return resourceDict;
}
/// <summary>
/// 从外部指定文件中加载图片
/// </summary>
/// <param name="filePath">图片文件的完整路径</param>
/// <returns>加载成功的 Texture2D 对象,或加载失败时返回 null</returns>
public static Texture2D LoadTextureByIO(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
Debug.LogError("文件路径为空,请检查输入!");
return null;
}
// 检查文件是否存在
if (!System.IO.File.Exists(filePath))
{
Debug.LogError($"文件不存在: {filePath}");
return null;
}
byte[] bytes = null;
try
{
// 使用 using 自动管理 FileStream 的生命周期
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
fs.Seek(0, SeekOrigin.Begin); // 将游标移动到文件开头(可选)
bytes = new byte[fs.Length]; // 创建一个字节数组来存储文件内容
fs.Read(bytes, 0, bytes.Length); // 读取文件内容到字节数组
}
}
catch (Exception e)
{
Debug.LogError($"读取文件时发生错误: {e.Message}");
return null;
}
// 创建一个默认大小的 Texture2D 对象
Texture2D texture = new Texture2D(2, 2); // 初始大小为 2x2LoadImage 会自动调整大小
if (texture.LoadImage(bytes)) // 加载图片数据
{
return texture; // 返回加载成功的 Texture2D 对象
}
else
{
Debug.LogError("图片加载失败,请检查文件格式是否正确!");
return null;
}
}
}
}