(client) feat:添加自定义瓦片和图片资源自定义加载 (#38)

Co-authored-by: zzdxxz <2079238449@qq.com>
Co-committed-by: zzdxxz <2079238449@qq.com>
This commit is contained in:
2025-07-17 15:42:24 +08:00
committed by TheRedApricot
parent ffeb65ba6b
commit 44cfb55985
42 changed files with 461 additions and 70 deletions

View File

@ -1,9 +1,12 @@
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
@ -284,5 +287,57 @@ namespace Configs
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;
}
}
}
}