Table of contents
Implemented:
Custom tool: excel to txt
game configuration class (process the data in txt and store it as an in-game ready-to-use data object
1. MenuItem-customization tool
1.1 Parameter introduction
Menultem is a feature that modifies a static method so that the corresponding button can appear on the top menu of Unity.
Menultem has three parameters:
1. Path: string type, use "/" to separate the path.
2. Whether it is a verification function: bool type, default is false.
3. Function priority: affects the order of appearance on the panel. The default is 1000. The smaller the value, the higher it appears.
Example:
[Menultem("Test/manqi",false,1000)]
public static void Log(){
Debug.Log("Success!");
}
1.2 Verification function
The second parameter of Menultem is a bool value used to determine whether the verification function is enabled.
Example:
[MenuItem("Test/manqi",false,1000)]
public static void Test(){
Debug.Log("Success!");
}
[MenuItem("Test/manqi",true,1000)]
public static bool ValidateTest(){
//是否选中物体
return Selection.activeTransform != null;
}
When no object is selected:
When an object is selected:
The second method here is a verification of the first method. If a transform is selected, it returns true; otherwise, it returns false. Its return value determines whether the first method is clickable.
It should be noted that the paths of the two methods need to be the same, and the second parameter of the verification method must be filled in with true, and the return value must be of type bool.
1.3 Results
Code:
using UnityEditor; //Unity编辑器的命名空间
public class MyEditor{
[MenuItem("我的工具/excel转txt")]
public static void ExportExcelToTxt(){
...}
}
Effect:
2. convert excel to txt
2.1 Preparation
Excel table to be converted:
Excel related plug-ins:
Create two folders:
Editor/MyEditor.cs //建立Editor存储MyEditor脚本,前面一步建立过了
Resources/Data //在Resources文件夹下建立Data文件用来存储转换完成的txt文件
2.2 Code
The steps to complete the code part are: get the excel file -> read the Excel file -> create txt text -> store excel as txt text.
2.2.1 Namespace
using UnityEditor; //Unity编辑器的命名空间,前面一个添加过了
using System.IO; //文件流的命名空间
using Exccel; //excel的命名空间
using System.Data;
2.2.2 MenuItem
[MenuItem("我的工具/excel转txt")]
public static void ExportExcelToTxt(){
...}
2.2.3 Define path
Define input path
private static string InPath = Application.dataPath+"/_Excel"; //输入路径
private static string OutPath = Application.dataPath+"/Resources/Data/"; //输出路径
2.2.4 Reading excel
[MenuItem("我的工具/excel转txt")]
public static void ExportExcelToTxt() {
//1.判断路径是否存在
if (Directory.Exists(InPath) == false) {
Debug.Log("路径不存在");
return;
}
//2.读取excel
string[] filesArr = Directory.GetFiles(InPath, "*.xlsx"); //*指所有符合要求的文件
for(int i = 0; i < filesArr.Length; i++) {
string filePath = filesArr[i].Replace("\\", "/"); //处理路径
using(FileStream fs = new FileStream(filePath, FileMode.Open)) {
//文件流读取
//这个方法是插件提供的,把文件流转换成excel对象
IExcelDataReader dataReader = ExcelReaderFactory.CreateOpenXmlReader(fs);
DataSet dataSet = dataReader.AsDataSet(); //DataSet是每个excel里面的工作簿
DataTable dataTable = dataSet.Tables[0]; //第一个工作簿
//这里应该写入txt
//...
}
}
}
2.2.5 Create txt and write text
private static void TableToTxt(DataTable dataTable,string filePath){
//获取不带后缀的文件名
string fileName = Path.GetFileNameWithoutExtension(filePath);
//创建txt文件
string path = OutPath + fileName + ".txt";
if (File.Exists(path)) File.Delete(path);
using(FileStream fs = new FileStream(path, FileMode.Create)) {
//文件流转写入流,方便写入字符串
using (StreamWriter sw = new StreamWriter(fs)) {
for(int row = 0; row < dataTable.Rows.Count; row++) {
for(int col = 0; col < dataTable.Columns.Count; col++) {
string val = dataTable.Rows[row][col].ToString();
sw.Write(val + "\t");
}
if (row != dataTable.Rows.Count - 1) sw.WriteLine();
}
}
}
}
2.2.6 Complete code
using UnityEngine;
using UnityEditor;
using System.IO;
using Excel;
using System.Data;
/// <summary>
/// 编辑器脚本
/// </summary>
public class MyEditor {
//1 路径
private static string InPath = Application.dataPath + "/_Excel";
private static string OutPath = Application.dataPath + "/Resources/Data/";
//2 读取excel
[MenuItem("我的工具/excel转txt")]
public static void ExportExcelToTxt() {
//2.1 判断路径是否存在
if (!Directory.Exists(InPath)) {
Debug.Log("路径不存在");
return;
}
//2.2 读取excel
string[] filesArr = Directory.GetFiles(InPath, "*.xlsx"); //获取全部.xlsx文件
for(int i = 0; i < filesArr.Length; i++) {
string filePath = filesArr[i].Replace("\\", "/");
using(FileStream fs = new FileStream(filePath, FileMode.Open)) {
//把文件流转换成excel对象
IExcelDataReader dataReader = ExcelReaderFactory.CreateOpenXmlReader(fs);
DataSet dataSet = dataReader.AsDataSet(); //dataSet是每个excel里面的工作簿
DataTable dataTable = dataSet.Tables[0];
//写入txt
TableTotxt(dataTable, filePath);
}
}
//2.3 刷新编辑器
AssetDatabase.Refresh();
}
//3 创建txt并写入
private static void TableTotxt(DataTable dataTable,string filePath) {
//获取不带后缀的文件名
string fileName = Path.GetFileNameWithoutExtension(filePath);
//创建txt文件
string path = OutPath + fileName + ".txt";
if (File.Exists(path)) File.Delete(path);
using(FileStream fs = new FileStream(path, FileMode.Create)) {
//文件流转写入流,方便写入字符串
using (StreamWriter sw = new StreamWriter(fs)) {
for(int row = 0; row < dataTable.Rows.Count; row++) {
for(int col = 0; col < dataTable.Columns.Count; col++) {
string val = dataTable.Rows[row][col].ToString();
sw.Write(val + "\t");
}
if (row != dataTable.Rows.Count - 1) sw.WriteLine();
}
}
}
}
}
2.3 Results
3. Game configuration class
3.1 Game configuration table class
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using UnityEngine;
/// <summary>
/// 游戏配置表类,每个对象对应一个txt配置表
/// </summary>
public class GameConfigData{
//存储配置表中的所有数据
private List<Dictionary<string, string>> dataDic;
//1.初始化
public GameConfigData(string str) {
//1.1 实例化
dataDic = new List<Dictionary<string, string>>();
//1.2 获取txt表格并处理数据
string[] lines = str.Split('\n'); //分行-换行符切割
string[] title = lines[0].Trim().Split('\t'); //分列-Tab切割(标题
for(int i = 2; i < lines.Length; i++) {
//从第三行开始遍历数据,第二行数据是解释说明
Dictionary<string, string> dic = new Dictionary<string, string>();
string[] tempArr = lines[i].Trim().Split('\t');
for(int j = 0; j < tempArr.Length; j++) {
dic.Add(title[j],tempArr[j]);
}
dataDic.Add(dic);
}
}
//2.获取数据表
public List<Dictionary<string,string>> GetLines() {
return dataDic;
}
//3.获取某行
public Dictionary<string,string> GetOneById(string id) {
for(int i = 0; i < dataDic.Count; i++) {
Dictionary<string, string> dic = dataDic[i];
if (dic["Id"] == id) return dic;
}
return null;
}
}
3.2 Game configuration table manager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 游戏配置表管理器
/// </summary>
public class GameConfigManager
{
public static GameConfigManager Instance = new GameConfigManager();
private GameConfigData cardData; //卡牌表
private GameConfigData enemyData; //敌人表
private GameConfigData levelData; //关卡表
private TextAsset textAsset;
//1.初始化配置文件(txt文件 存储在内存中)
public void Init() {
textAsset = Resources.Load<TextAsset>("Data/card");
cardData = new GameConfigData(textAsset.text);
textAsset = Resources.Load<TextAsset>("Data/enemy");
enemyData = new GameConfigData(textAsset.text);
textAsset = Resources.Load<TextAsset>("Data/level");
levelData = new GameConfigData(textAsset.text);
}
//2.获取数据表
public List<Dictionary<string,string>> GetCardLines() {
return cardData.GetLines();
}
public List<Dictionary<string, string>> GetEnemyLines() {
return enemyData.GetLines();
}
public List<Dictionary<string, string>> GetlevelLines() {
return levelData.GetLines();
}
//3.获取id对应某行
public Dictionary<string,string> GetCardById(string id) {
return cardData.GetOneById(id);
}
public Dictionary<string, string> GetEnemyById(string id) {
return enemyData.GetOneById(id);
}
public Dictionary<string, string> GetLevelById(string id) {
return levelData.GetOneById(id);
}
}
3.3 Results
Code: Add: to GameApp.cs:
string name = GameConfigManager.Instance.GetCardById("1001")["Name"];
Debug.Log(name);
result: