Unity读取表格数据
效果:
思路:
Unity可以解析Json,但是读取Excel需要插件的帮助,那就把这个功能分离开,读表插件就只管读表转Json,Unity就只管Json解析,中间需要一个存储空间,使用ScriptableObject数据类是个不错的选择。
缺点也很明显,我们只能在Unity编辑器模式下使用这个工具,也就是无法在打包后读取Excel,不过我们再也不用担心读表插件出问题了,因为打包后根本用不到读表插件。
实现步骤:
- 步骤一:Excel数据转换成Json数据
- 步骤二:将数据存储到ScriptableObject持久类中
- 步骤三:Unity读取ScriptableObject类
Excel数据转换成Json数据
因为只考虑在Unity编辑器模式使用,所以直接写一个编辑器窗口就行了
主要功能概述
- 用户界面(EditorWindow):提供一个界面让用户选择 Excel 文件,并进行相应的操作,如选择是否生成 C# 类文件、开始转换等。
- 文件处理:用户可以拖拽文件或文件夹到指定区域,程序会识别路径并加载 Excel 文件列表。
- 转换操作:Excel 文件被读取,转换为 JSON 数据,并保存到指定路径。
- 打开编辑窗口
[MenuItem("Tools/ExcelToJson")]
public static void ShowWindow()
{
ExcelToUnityWindow window = GetWindow<ExcelToUnityWindow>("Excel 转 Json 工具");
window.minSize = new Vector2(400 , 300);
}
这段代码创建了一个编辑器窗口,当用户点击 Unity 编辑器菜单中的 “Tools/ExcelToJson” 时,会弹出 ExcelToUnityWindow 窗口。
- 初始化并加载 JsonFileData
private void OnEnable()
{
csOutputPath = Path.Combine(Application.dataPath , "Tool/ExcelTool/ConfigData");
jsonFileCollector = Resources.Load<JsonFileData>("JsonFileCollector");
if (jsonFileCollector == null)
Debug.LogError("未找到 JsonFileCollector 实例,请确保已创建该资产文件!");
RefreshFileList();
}
OnEnable 方法会在编辑器窗口启用时调用,它会加载 JsonFileCollector 实例,这个实例用于管理 JSON 数据。
- 文件夹路径选择与拖拽支持
private void HandleDragAndDrop(Rect dropArea)
{
Event evt = Event.current;
if (evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if (evt.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
if (DragAndDrop.paths.Length > 0)
{
string draggedPath = DragAndDrop.paths[0];
if (File.Exists(draggedPath) && draggedPath.EndsWith(".xlsx"))
{
folderPath = Path.GetDirectoryName(draggedPath);
}
else if (Directory.Exists(draggedPath))
{
folderPath = draggedPath;
}
RefreshFileList();
}
evt.Use();
}
}
}
}
这个方法实现了拖拽功能,用户可以将文件或文件夹拖拽到指定区域,程序会检测并更新路径。
- 转换文件的核心操作
private void ConvertExcelFiles()
{
foreach (string filePath in selectedExcelFiles)
{
ParseFile(filePath , createCS , csOutputPath);
}
EditorUtility.DisplayDialog("完成" , "所有 Excel 文件已成功转换!" , "确定");
}
ConvertExcelFiles() 方法会遍历用户选择的 Excel 文件,并调用 ParseFile() 方法来处理每一个文件。这个方法的核心功能是将 Excel 文件转换为 JSON 格式。
- Excel 文件解析与 JSON 转换
private static string ParseFile(string path , bool createCS , string csOutputPath)
{
if (!path.EndsWith("xlsx")) return null;
string tableName = "";
string cfgName = "";
Excel excel = null;
try
{
(Excel a, string b) temp = ExcelHelper.LoadExcel(path);
excel = temp.a;
cfgName = temp.b;
StringBuilder sb = new StringBuilder();
JsonWriter writer = new JsonWriter(sb);
writer.WriteObjectStart();
foreach (ExcelTable table in excel.Tables