这样做的目的有助于策划改需求时。可以直接热更新修改游戏数值。
过程中还会设计变量类型来判断是否添加引号
using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.Text;
using UnityEditor;
public class test : MonoBehaviour {
[MenuItem("Tools/CsvToLua")]
public static void csvToLua()
{
DirectoryInfo dinfo = new DirectoryInfo(Application.dataPath + "/Csv/");
if (dinfo.Exists)
{
FileInfo[] infos = dinfo.GetFiles();
foreach (var info in infos)
{
//判断是否是CSV文件,排除META文件
if (Path.GetExtension(Application.dataPath + "/Csv/" + info.Name) != ".csv")
{
continue;
}
//读取文件 在根目录的Csv文件夹中存放Csv文件
FileStream fs = new FileStream(Application.dataPath + "/Csv/" + info.Name, FileMode.Open, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs, Encoding.UTF8);
//存储文件 存储到CsvToLua中
File.Delete(Application.dataPath + "/CsvToLua/" + info.Name + ".lua");
FileStream csvToLua = new FileStream(Application.dataPath + "/CsvToLua/" + info.Name + ".lua", FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(csvToLua);
//以文件作为表名
sw.WriteLine(Path.GetFileNameWithoutExtension(info.Name) + " {");
string[] title;
List<string> lineArray = new List<string>();
while(sr.Peek() != -1)
{
lineArray.Add(sr.ReadLine());
}
//读取第一行属性
string[] datas = lineArray[0].ToString().Split(',');
title = new string[datas.Length];
for (int k = 0; k < datas.Length; k++)
{
title[k] = datas[k];
}
for (int i = 0; i < lineArray.Count; i++)
{
datas = lineArray[i].Split(',');
sw.Write("[" + datas[0] + "] = {");
for (int j = 0; j < datas.Length; j++)
{
sw.Write("\"" + title[j] + "\"=" + datas[j].Trim());
if (j != datas.Length - 1)
{
sw.Write(", ");
}
}
if (i != lineArray.Count -1)
{
sw.WriteLine("},");
}
}
sw.WriteLine("}");
sw.Write("}");
sw.Close();
}
}
}
}