1. 程式人生 > >【Unity開發】通過C#讀取CSV表,建立並存儲到LUA table中

【Unity開發】通過C#讀取CSV表,建立並存儲到LUA table中

這樣做的目的有助於策劃改需求時。可以直接熱更新修改遊戲數值。

過程中還會設計變數型別來判斷是否新增引號

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();
            }
        }
    }
   
}