[Diario de desarrollo del juego 02] Procesamiento de tablas de información de Excel

Implementado:
herramienta personalizada: clase de configuración del juego de excel a txt
(procesa los datos en txt y guárdalos como un objeto de datos listo para usar en el juego).

1. Herramienta de personalización MenuItem

1.1 Introducción de parámetros

Menultem es una característica que modifica un método estático para que el botón correspondiente pueda aparecer en el menú superior de Unity.

Menultem tiene tres parámetros:
1. Ruta: tipo de cadena, use "/" para separar la ruta.
2. Si se trata de una función de verificación: tipo bool, el valor predeterminado es falso.
3. Prioridad de función: afecta el orden de aparición en el panel, el valor predeterminado es 1000. Cuanto menor es el valor, más alto aparece.

Ejemplo:

[Menultem("Test/manqi",false,1000)]
public static void Log(){
    
    
	Debug.Log("Success!");
}

Ejemplo de menú
Ejemplo de menú

1.2 Función de verificación

El segundo parámetro de Menultem es un valor bool que se utiliza para determinar si la función de verificación está habilitada.

Ejemplo:

[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;
}

Cuando no se selecciona ningún objeto:

Ejemplo de menú
Cuando se selecciona un objeto:

menuletm
El segundo método aquí es una verificación del primer método. Si se selecciona una transformación, devuelve verdadero; de lo contrario, devuelve falso. Su valor de retorno determina si se puede hacer clic en el primer método.

Cabe señalar que las rutas de los dos métodos deben ser las mismas, el segundo parámetro del método de verificación debe completarse con verdadero y el valor de retorno debe ser de tipo bool.

1.3 Resultados

Código:

using UnityEditor;  //Unity编辑器的命名空间
public class MyEditor{
    
    
	[MenuItem("我的工具/excel转txt")]
	public static void ExportExcelToTxt(){
    
    ...}
}

Efecto:

Opción del menú

2. convertir excel a txt

2.1 Preparación

Tabla de Excel a convertir:

sobresalir
Complementos relacionados con Excel:

sobresalir
Crea dos carpetas:

Editor/MyEditor.cs   //建立Editor存储MyEditor脚本,前面一步建立过了
Resources/Data       //在Resources文件夹下建立Data文件用来存储转换完成的txt文件

2.2 Código

Los pasos para completar la parte del código son: obtener el archivo de Excel -> leer el archivo de Excel -> crear texto de texto -> almacenar Excel como texto de texto.

2.2.1 Espacio de nombres

using UnityEditor;  //Unity编辑器的命名空间,前面一个添加过了
using System.IO;    //文件流的命名空间
using Exccel;       //excel的命名空间
using System.Data;  

2.2.2 Elemento de menú

[MenuItem("我的工具/excel转txt")]
public static void ExportExcelToTxt(){
    
    ...}

2.2.3 Definir ruta

Definir ruta de entrada

private static string InPath = Application.dataPath+"/_Excel";               //输入路径
private static string OutPath = Application.dataPath+"/Resources/Data/";     //输出路径

2.2.4 Lectura de 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 Crear txt y escribir texto

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 Código completo

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 Resultados

resultado

3. Clase de configuración del juego.

3.1 Clase de tabla de configuración del juego

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 Administrador de la tabla de configuración del juego

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 Resultados

Código: Agregar: a GameApp.cs:

string name = GameConfigManager.Instance.GetCardById("1001")["Name"];
Debug.Log(name);

resultado:

prueba

Supongo que te gusta

Origin blog.csdn.net/manpi/article/details/129262415
Recomendado
Clasificación