前言:
去年还是小菜鸡的我写过在Unity中单选题和多选题的开发。现在进步一点点,这次可以直接编辑表格,在表格中增删改查数据即可,无需再对代码进行更改!
下载链接在文章末尾,需要的可以直接划到最后!
废话不多说,开始~
首先需要配置三个文件
- 读取表格的程序集:EPPlus
- 处理Json数据的程序集:Newtonsoft.Json
- 表格文件:question.xlsx
大概流程如下
创建StreamingAssets文件
-
首先我们在工程文件Assets文件下创建一个StreamingAssets(这里我们默认使用此路径为加载路径)
-
我们在此文件夹下创建一个表格。这里我使用的是.xlsx
下面是表结构,大家如果要修改的话,记得同时修改Question.cs哦!
创建Plugins文件
-
在Assets文件下创建一个名为Plugins文件夹
-
将刚才上面说了两个程序集EPPlus和Newtonsoft.Json放入此文件下
做完上面那些就可以导入我给大伙准备的脚本了
这里一共有三个脚本:
- ExcelMgr.cs
- Question.cs
- UIQuesPanel.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using OfficeOpenXml;
using System.IO;
using System.Data;
using System;
using Newtonsoft.Json.Linq;
using DialogEntity;
namespace vvb_ExcelMgr
{
public class ExcelMgr : MonoBehaviour
{
static ExcelPackage package;//表文件缓存
public static ExcelWorkbook dialogWorkbook;//表工作簿
public List<Question> questionList = new List<Question>();//题目缓存列表
public string quesPackPath="question";//题目文件地址,文件后缀默认为".xlsx"
private void Awake()
{
ReadExcel(quesPackPath, () =>
{
UIQuesPanel.quesList = GetQuesList(package);
questionList = UIQuesPanel.quesList;//这里为了在inspecter中能看到读取到达数据
});
}
/// <summary>
/// 打开表缓存
/// </summary>
public static ExcelWorkbook ReadExcel(string excelPath, Action action)
{
//Debug.Log(Application.streamingAssetsPath);
excelPath = Application.streamingAssetsPath + "/"+excelPath+".xlsx";
try
{
using (package = new ExcelPackage(new FileStream(excelPath, FileMode.Open)))
{
action?.Invoke();
return package.Workbook;
}
}
catch (NullReferenceException e)
{
Debug.LogError("空指针异常:" + e);
return null;
}
catch (IOException e)
{
Debug.LogError("文件打开异常:" + e);
return null;
}
catch (Exception e)
{
Debug.LogError("其他异常:" + e);
return null