• unity学习(五):Excel表格读取和数据类生成


    idpetNamepetAvtdescription
    stringstringstringstring
    1软绵绵PetAvt1一只可爱的小绵羊,但是千万不要被它的外表所迷惑
    2鸵鸟-KLPetAvt2理想城中的机械宠物,能够辅助赛车手进行比赛
    3军火猪PetAvt4一只暴躁的虎皮猪,总是横冲直撞的破坏着

    表格格式固定,第一行数据名 ,第二行数据类型,

    第一行和第一列为非重复数据,防止读取冲突

    1、选取表格,另存为.csv文件,生成的.csv需要转换为UTF-8格式,不然读取会有问题 

    2、生成解析csv窗口

    Editor/CreatConfigDataFile.cs

    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEditor;
    5. ///
    6. /// Excel表格的解析窗口
    7. ///
    8. public class CreatConfigDataFile : EditorWindow {
    9. static string writePath = "/Scripts/GameConfigs/";
    10. static Object selectObj;
    11. [MenuItem("framework/打开配置Excel表格的解析窗口")]
    12. static void ByWindow()
    13. {
    14. CreatConfigDataFile window = EditorWindow.GetWindow();
    15. }
    16. private void OnGUI()
    17. {
    18. GUILayout.Label("设置配置数据文件的生成路径");
    19. writePath = GUILayout.TextField(writePath);
    20. GUILayout.Label("请选择一个合法的CSV文件");
    21. if (GUILayout.Button("生成C#协议文件"))
    22. {
    23. Debug.Log("生成C#协议文件----------");
    24. if (selectObj != null)
    25. {
    26. CreatConfigUitl.CreatConfigFile(selectObj, writePath);
    27. }
    28. }
    29. if (Selection.activeObject != null)
    30. {
    31. string path = AssetDatabase.GetAssetPath(Selection.activeObject);
    32. if (path.ToLower().Substring(path.Length - 4, 4) == ".csv")
    33. {
    34. selectObj = Selection.activeObject;
    35. GUILayout.Label(path);
    36. }
    37. }
    38. }
    39. private void OnSelectionChange()
    40. {
    41. Repaint();
    42. }
    43. }

     

     3、读取csv,并自动生成对应数据类

    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. using System.Text;
    5. using System.IO;
    6. ///
    7. /// CSV 读写
    8. ///
    9. public class CsvStreamReader
    10. {
    11. private ArrayList rowAL; //行链表,CSV文件的每一行就是一个链
    12. private string fileName; //文件名
    13. private Encoding encoding; //编码
    14. ///
    15. ///
    16. ///
    17. /// 文件名,包括文件路径
    18. public CsvStreamReader(string fileName)
    19. {
    20. this.rowAL = new ArrayList();
    21. this.fileName = fileName;
    22. this.encoding = Encoding.Default;
    23. LoadCsvFile();
    24. }
    25. ///
    26. ///
    27. ///
    28. /// 文件名,包括文件路径
    29. /// 文件编码
    30. public CsvStreamReader(string fileName,Encoding encoding)
    31. {
    32. this.rowAL = new ArrayList();
    33. this.fileName = fileName;
    34. this.encoding = encoding;
    35. LoadCsvFile();
    36. }
    37. ///
    38. /// 文件名,包括文件路径
    39. ///
    40. public string FileName
    41. {
    42. set
    43. {
    44. this.fileName = value;
    45. LoadCsvFile();
    46. }
    47. }
    48. ///
    49. /// 文件编码
    50. ///
    51. public Encoding FileEncoding
    52. {
    53. set
    54. {
    55. this.encoding = value;
    56. }
    57. }
    58. ///
    59. /// 获取行数
    60. ///
    61. public int RowCount
    62. {
    63. get
    64. {
    65. return this.rowAL.Count;
    66. }
    67. }
    68. ///
    69. /// 获取列数
    70. ///
    71. public int ColCount
    72. {
    73. get
    74. {
    75. int maxCol;
    76. maxCol = 0;
    77. for (int i = 0;i<this.rowAL.Count;i++)
    78. {
    79. ArrayList colAL = (ArrayList) this.rowAL[i]; //rowAL中的某个元素依然是ArrayList类型
    80. maxCol = (maxCol > colAL.Count)?maxCol:colAL.Count; //取最大值
    81. }
    82. return maxCol;
    83. }
    84. }
    85. ///
    86. /// 获取某行某列的数据
    87. /// row:行,row = 1代表第一行
    88. /// col:列,col = 1代表第一列
    89. ///
    90. public string this[int row,int col]
    91. {
    92. get
    93. {
    94. //数据有效性验证
    95. CheckRowValid(row);
    96. CheckColValid(col);
    97. ArrayList colAL = (ArrayList) this.rowAL[row-1];
    98. //如果请求列数据大于当前行的列时,返回空值
    99. if (colAL.Count < col)
    100. {
    101. return "";
    102. }
    103. return colAL[col-1].ToString();
    104. }
    105. }
    106. ///
    107. /// 根据最小行,最大行,最小列,最大列,来生成一个DataTable类型的数据
    108. /// 行等于1代表第一行
    109. ///
    110. /// 检查行数是否是有效的
    111. ///
    112. ///
    113. private void CheckRowValid(int row)
    114. {
    115. if (row <= 0)
    116. {
    117. throw new Exception("行数不能小于0");
    118. }
    119. if (row > RowCount)
    120. {
    121. throw new Exception("没有当前行的数据");
    122. }
    123. }
    124. ///
    125. /// 检查最大行数是否是有效的
    126. ///
    127. ///
    128. private void CheckMaxRowValid(int maxRow)
    129. {
    130. if (maxRow <= 0 && maxRow != -1)
    131. {
    132. throw new Exception("行数不能等于0或小于-1");
    133. }
    134. if (maxRow > RowCount)
    135. {
    136. throw new Exception("没有当前行的数据");
    137. }
    138. }
    139. ///
    140. /// 检查列数是否是有效的
    141. ///
    142. ///
    143. private void CheckColValid(int col)
    144. {
    145. if (col <= 0)
    146. {
    147. throw new Exception("列数不能小于0");
    148. }
    149. if (col > ColCount)
    150. {
    151. throw new Exception("没有当前列的数据");
    152. }
    153. }
    154. ///
    155. /// 检查检查最大列数是否是有效的
    156. ///
    157. ///
    158. private void CheckMaxColValid(int maxCol)
    159. {
    160. if (maxCol <= 0 && maxCol != -1)
    161. {
    162. throw new Exception("列数不能等于0或小于-1");
    163. }
    164. if (maxCol > ColCount)
    165. {
    166. throw new Exception("没有当前列的数据");
    167. }
    168. }
    169. ///
    170. /// 载入CSV文件
    171. ///
    172. private void LoadCsvFile()
    173. {
    174. //对数据的有效性进行验证
    175. if (this.fileName == null)
    176. {
    177. throw new Exception("请指定要载入的CSV文件名");
    178. }
    179. else if (!File.Exists(this.fileName))
    180. {
    181. throw new Exception("指定的CSV文件不存在");
    182. }
    183. else
    184. {
    185. }
    186. if (this.encoding == null)
    187. {
    188. this.encoding = Encoding.Default;
    189. }
    190. StreamReader sr = new StreamReader(this.fileName,this.encoding);
    191. string csvDataLine;
    192. csvDataLine = "";
    193. while (true)
    194. {
    195. string fileDataLine;
    196. fileDataLine = sr.ReadLine();
    197. if (fileDataLine == null)
    198. {
    199. break;
    200. }
    201. if (csvDataLine == "")
    202. {
    203. csvDataLine = fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
    204. }
    205. else
    206. {
    207. csvDataLine += "/r/n" + fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
    208. }
    209. //如果包含偶数个引号,说明该行数据中出现回车符或包含逗号
    210. if (!IfOddQuota(csvDataLine))
    211. {
    212. AddNewDataLine(csvDataLine);
    213. csvDataLine = "";
    214. }
    215. }
    216. sr.Close();
    217. //数据行出现奇数个引号
    218. if (csvDataLine.Length > 0)
    219. {
    220. throw new Exception("CSV文件的格式有错误");
    221. }
    222. }
    223. ///
    224. /// 获取两个连续引号变成单个引号的数据行
    225. ///
    226. /// 文件数据行
    227. ///
    228. private string GetDeleteQuotaDataLine(string fileDataLine)
    229. {
    230. return fileDataLine.Replace("\"\"","\"");
    231. }
    232. ///
    233. /// 判断字符串是否包含奇数个引号
    234. ///
    235. /// 数据行
    236. /// 为奇数时,返回为真;否则返回为假
    237. private bool IfOddQuota(string dataLine)
    238. {
    239. int quotaCount;
    240. bool oddQuota;
    241. quotaCount = 0;
    242. for (int i = 0;i < dataLine.Length;i++)
    243. {
    244. if (dataLine[i] == '\"')
    245. {
    246. quotaCount++;
    247. }
    248. }
    249. oddQuota = false;
    250. if (quotaCount % 2 == 1)
    251. {
    252. oddQuota = true;
    253. }
    254. return oddQuota;
    255. }
    256. ///
    257. /// 判断是否以奇数个引号开始
    258. ///
    259. ///
    260. ///
    261. private bool IfOddStartQuota(string dataCell)
    262. {
    263. int quotaCount;
    264. bool oddQuota;
    265. quotaCount = 0;
    266. for (int i = 0;i < dataCell.Length;i++)
    267. {
    268. if (dataCell[i] == '\"')
    269. {
    270. quotaCount++;
    271. }
    272. else
    273. {
    274. break;
    275. }
    276. }
    277. oddQuota = false;
    278. if (quotaCount % 2 == 1)
    279. {
    280. oddQuota = true;
    281. }
    282. return oddQuota;
    283. }
    284. ///
    285. /// 判断是否以奇数个引号结尾
    286. ///
    287. ///
    288. ///
    289. private bool IfOddEndQuota(string dataCell)
    290. {
    291. int quotaCount;
    292. bool oddQuota;
    293. quotaCount = 0;
    294. for (int i = dataCell.Length -1;i >= 0;i--)
    295. {
    296. if (dataCell[i] == '\"')
    297. {
    298. quotaCount++;
    299. }
    300. else
    301. {
    302. break;
    303. }
    304. }
    305. oddQuota = false;
    306. if (quotaCount % 2 == 1)
    307. {
    308. oddQuota = true;
    309. }
    310. return oddQuota;
    311. }
    312. ///
    313. /// 加入新的数据行
    314. ///
    315. /// 新的数据行
    316. private void AddNewDataLine(string newDataLine)
    317. {
    318. Debug.Log("NewLine:" + newDataLine);
    319. //return;
    320. ArrayList colAL = new ArrayList();
    321. string[] dataArray = newDataLine.Split(',');
    322. bool oddStartQuota; //是否以奇数个引号开始
    323. string cellData;
    324. oddStartQuota = false;
    325. cellData = "";
    326. for (int i = 0 ;i < dataArray.Length;i++)
    327. {
    328. if (oddStartQuota)
    329. {
    330. //因为前面用逗号分割,所以要加上逗号
    331. cellData += "," + dataArray[i];
    332. //是否以奇数个引号结尾
    333. if (IfOddEndQuota(dataArray[i]))
    334. {
    335. colAL.Add(GetHandleData(cellData));
    336. oddStartQuota = false;
    337. continue;
    338. }
    339. }
    340. else
    341. {
    342. //是否以奇数个引号开始
    343. if (IfOddStartQuota(dataArray[i]))
    344. {
    345. //是否以奇数个引号结尾,不能是一个双引号,并且不是奇数个引号
    346. if (IfOddEndQuota(dataArray[i]) && dataArray[i].Length > 2 && !IfOddQuota(dataArray[i]))
    347. {
    348. colAL.Add(GetHandleData(dataArray[i]));
    349. oddStartQuota = false;
    350. continue;
    351. }
    352. else
    353. {
    354. oddStartQuota = true;
    355. cellData = dataArray[i];
    356. continue;
    357. }
    358. }
    359. else
    360. {
    361. colAL.Add(GetHandleData(dataArray[i]));
    362. }
    363. }
    364. }
    365. if (oddStartQuota)
    366. {
    367. throw new Exception("数据格式有问题");
    368. }
    369. this.rowAL.Add(colAL);
    370. }
    371. ///
    372. /// 去掉格子的首尾引号,把双引号变成单引号
    373. ///
    374. ///
    375. ///
    376. private string GetHandleData(string fileCellData)
    377. {
    378. if (fileCellData == "")
    379. {
    380. return "";
    381. }
    382. if (IfOddStartQuota(fileCellData))
    383. {
    384. if (IfOddEndQuota(fileCellData))
    385. {
    386. return fileCellData.Substring(1,fileCellData.Length-2).Replace("\"\"","\""); //去掉首尾引号,然后把双引号变成单引号
    387. }
    388. else
    389. {
    390. throw new Exception("数据引号无法匹配" + fileCellData);
    391. }
    392. }
    393. else
    394. {
    395. //考虑形如"" """" """"""
    396. if (fileCellData.Length >2 && fileCellData[0] == '\"')
    397. {
    398. fileCellData = fileCellData.Substring(1,fileCellData.Length-2).Replace("\"\"","\""); //去掉首尾引号,然后把双引号变成单引号
    399. }
    400. }
    401. return fileCellData;
    402. }
    403. }

    CreatConfigUitl.cs 

    1. using UnityEngine;
    2. using System.IO;
    3. using UnityEditor;
    4. ///
    5. /// 自动化生成csv文件对应数据类
    6. ///
    7. public class CreatConfigUitl {
    8. public static void CreatConfigFile(Object selectObj, string writePath)
    9. {
    10. string fileName = selectObj.name;
    11. string className = fileName;
    12. if (Directory.Exists(Application.dataPath + writePath) == false)
    13. {
    14. Directory.CreateDirectory(Application.dataPath + writePath);
    15. }
    16. StreamWriter sw = new StreamWriter(Application.dataPath + writePath + className + ".cs");
    17. sw.WriteLine("using UnityEngine;\nusing System.Collections;\n");
    18. sw.WriteLine("public partial class " + className + " : GameConfigDataBase");
    19. sw.WriteLine("{");
    20. string filePath = AssetDatabase.GetAssetPath(selectObj);
    21. CsvStreamReader csr = new CsvStreamReader(filePath);
    22. for (int colNum = 1; colNum < csr.ColCount + 1; colNum++)
    23. {
    24. string fieldName = csr[1, colNum];
    25. string fieldType = csr[2, colNum];
    26. sw.WriteLine("\t" + "public " + fieldType + " " + fieldName + ";" + "");
    27. }
    28. sw.WriteLine("\t" + "protected override string getFilePath ()");
    29. sw.WriteLine("\t" + "{");
    30. // filePath=filePath.Replace("Assets/Resources/","");
    31. // filePath=filePath.Substring(0,filePath.LastIndexOf('.'));
    32. sw.WriteLine("\t\t" + "return " + "\"" + fileName + "\";");
    33. sw.WriteLine("\t" + "}");
    34. sw.WriteLine("}");
    35. sw.Flush();
    36. sw.Close();
    37. AssetDatabase.Refresh(); //这里是一个点
    38. }
    39. }

     CsvStreamReader.cs  游戏内数据读取解析

    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. using System.Text;
    5. using System.IO;
    6. ///
    7. /// CSV 读写
    8. ///
    9. public class CsvStreamReader
    10. {
    11. private ArrayList rowAL; //行链表,CSV文件的每一行就是一个链
    12. private string fileName; //文件名
    13. private Encoding encoding; //编码
    14. ///
    15. ///
    16. ///
    17. /// 文件名,包括文件路径
    18. public CsvStreamReader(string fileName)
    19. {
    20. this.rowAL = new ArrayList();
    21. this.fileName = fileName;
    22. this.encoding = Encoding.Default;
    23. LoadCsvFile();
    24. }
    25. ///
    26. ///
    27. ///
    28. /// 文件名,包括文件路径
    29. /// 文件编码
    30. public CsvStreamReader(string fileName,Encoding encoding)
    31. {
    32. this.rowAL = new ArrayList();
    33. this.fileName = fileName;
    34. this.encoding = encoding;
    35. LoadCsvFile();
    36. }
    37. ///
    38. /// 文件名,包括文件路径
    39. ///
    40. public string FileName
    41. {
    42. set
    43. {
    44. this.fileName = value;
    45. LoadCsvFile();
    46. }
    47. }
    48. ///
    49. /// 文件编码
    50. ///
    51. public Encoding FileEncoding
    52. {
    53. set
    54. {
    55. this.encoding = value;
    56. }
    57. }
    58. ///
    59. /// 获取行数
    60. ///
    61. public int RowCount
    62. {
    63. get
    64. {
    65. return this.rowAL.Count;
    66. }
    67. }
    68. ///
    69. /// 获取列数
    70. ///
    71. public int ColCount
    72. {
    73. get
    74. {
    75. int maxCol;
    76. maxCol = 0;
    77. for (int i = 0;i<this.rowAL.Count;i++)
    78. {
    79. ArrayList colAL = (ArrayList) this.rowAL[i]; //rowAL中的某个元素依然是ArrayList类型
    80. maxCol = (maxCol > colAL.Count)?maxCol:colAL.Count; //取最大值
    81. }
    82. return maxCol;
    83. }
    84. }
    85. ///
    86. /// 获取某行某列的数据
    87. /// row:行,row = 1代表第一行
    88. /// col:列,col = 1代表第一列
    89. ///
    90. public string this[int row,int col]
    91. {
    92. get
    93. {
    94. //数据有效性验证
    95. CheckRowValid(row);
    96. CheckColValid(col);
    97. ArrayList colAL = (ArrayList) this.rowAL[row-1];
    98. //如果请求列数据大于当前行的列时,返回空值
    99. if (colAL.Count < col)
    100. {
    101. return "";
    102. }
    103. return colAL[col-1].ToString();
    104. }
    105. }
    106. ///
    107. /// 根据最小行,最大行,最小列,最大列,来生成一个DataTable类型的数据
    108. /// 行等于1代表第一行
    109. ///
    110. /// 检查行数是否是有效的
    111. ///
    112. ///
    113. private void CheckRowValid(int row)
    114. {
    115. if (row <= 0)
    116. {
    117. throw new Exception("行数不能小于0");
    118. }
    119. if (row > RowCount)
    120. {
    121. throw new Exception("没有当前行的数据");
    122. }
    123. }
    124. ///
    125. /// 检查最大行数是否是有效的
    126. ///
    127. ///
    128. private void CheckMaxRowValid(int maxRow)
    129. {
    130. if (maxRow <= 0 && maxRow != -1)
    131. {
    132. throw new Exception("行数不能等于0或小于-1");
    133. }
    134. if (maxRow > RowCount)
    135. {
    136. throw new Exception("没有当前行的数据");
    137. }
    138. }
    139. ///
    140. /// 检查列数是否是有效的
    141. ///
    142. ///
    143. private void CheckColValid(int col)
    144. {
    145. if (col <= 0)
    146. {
    147. throw new Exception("列数不能小于0");
    148. }
    149. if (col > ColCount)
    150. {
    151. throw new Exception("没有当前列的数据");
    152. }
    153. }
    154. ///
    155. /// 检查检查最大列数是否是有效的
    156. ///
    157. ///
    158. private void CheckMaxColValid(int maxCol)
    159. {
    160. if (maxCol <= 0 && maxCol != -1)
    161. {
    162. throw new Exception("列数不能等于0或小于-1");
    163. }
    164. if (maxCol > ColCount)
    165. {
    166. throw new Exception("没有当前列的数据");
    167. }
    168. }
    169. ///
    170. /// 载入CSV文件
    171. ///
    172. private void LoadCsvFile()
    173. {
    174. //对数据的有效性进行验证
    175. if (this.fileName == null)
    176. {
    177. throw new Exception("请指定要载入的CSV文件名");
    178. }
    179. else if (!File.Exists(this.fileName))
    180. {
    181. throw new Exception("指定的CSV文件不存在");
    182. }
    183. else
    184. {
    185. }
    186. if (this.encoding == null)
    187. {
    188. this.encoding = Encoding.Default;
    189. }
    190. StreamReader sr = new StreamReader(this.fileName,this.encoding);
    191. string csvDataLine;
    192. csvDataLine = "";
    193. while (true)
    194. {
    195. string fileDataLine;
    196. fileDataLine = sr.ReadLine();
    197. if (fileDataLine == null)
    198. {
    199. break;
    200. }
    201. if (csvDataLine == "")
    202. {
    203. csvDataLine = fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
    204. }
    205. else
    206. {
    207. csvDataLine += "/r/n" + fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
    208. }
    209. //如果包含偶数个引号,说明该行数据中出现回车符或包含逗号
    210. if (!IfOddQuota(csvDataLine))
    211. {
    212. AddNewDataLine(csvDataLine);
    213. csvDataLine = "";
    214. }
    215. }
    216. sr.Close();
    217. //数据行出现奇数个引号
    218. if (csvDataLine.Length > 0)
    219. {
    220. throw new Exception("CSV文件的格式有错误");
    221. }
    222. }
    223. ///
    224. /// 获取两个连续引号变成单个引号的数据行
    225. ///
    226. /// 文件数据行
    227. ///
    228. private string GetDeleteQuotaDataLine(string fileDataLine)
    229. {
    230. return fileDataLine.Replace("\"\"","\"");
    231. }
    232. ///
    233. /// 判断字符串是否包含奇数个引号
    234. ///
    235. /// 数据行
    236. /// 为奇数时,返回为真;否则返回为假
    237. private bool IfOddQuota(string dataLine)
    238. {
    239. int quotaCount;
    240. bool oddQuota;
    241. quotaCount = 0;
    242. for (int i = 0;i < dataLine.Length;i++)
    243. {
    244. if (dataLine[i] == '\"')
    245. {
    246. quotaCount++;
    247. }
    248. }
    249. oddQuota = false;
    250. if (quotaCount % 2 == 1)
    251. {
    252. oddQuota = true;
    253. }
    254. return oddQuota;
    255. }
    256. ///
    257. /// 判断是否以奇数个引号开始
    258. ///
    259. ///
    260. ///
    261. private bool IfOddStartQuota(string dataCell)
    262. {
    263. int quotaCount;
    264. bool oddQuota;
    265. quotaCount = 0;
    266. for (int i = 0;i < dataCell.Length;i++)
    267. {
    268. if (dataCell[i] == '\"')
    269. {
    270. quotaCount++;
    271. }
    272. else
    273. {
    274. break;
    275. }
    276. }
    277. oddQuota = false;
    278. if (quotaCount % 2 == 1)
    279. {
    280. oddQuota = true;
    281. }
    282. return oddQuota;
    283. }
    284. ///
    285. /// 判断是否以奇数个引号结尾
    286. ///
    287. ///
    288. ///
    289. private bool IfOddEndQuota(string dataCell)
    290. {
    291. int quotaCount;
    292. bool oddQuota;
    293. quotaCount = 0;
    294. for (int i = dataCell.Length -1;i >= 0;i--)
    295. {
    296. if (dataCell[i] == '\"')
    297. {
    298. quotaCount++;
    299. }
    300. else
    301. {
    302. break;
    303. }
    304. }
    305. oddQuota = false;
    306. if (quotaCount % 2 == 1)
    307. {
    308. oddQuota = true;
    309. }
    310. return oddQuota;
    311. }
    312. ///
    313. /// 加入新的数据行
    314. ///
    315. /// 新的数据行
    316. private void AddNewDataLine(string newDataLine)
    317. {
    318. Debug.Log("NewLine:" + newDataLine);
    319. //return;
    320. ArrayList colAL = new ArrayList();
    321. string[] dataArray = newDataLine.Split(',');
    322. bool oddStartQuota; //是否以奇数个引号开始
    323. string cellData;
    324. oddStartQuota = false;
    325. cellData = "";
    326. for (int i = 0 ;i < dataArray.Length;i++)
    327. {
    328. if (oddStartQuota)
    329. {
    330. //因为前面用逗号分割,所以要加上逗号
    331. cellData += "," + dataArray[i];
    332. //是否以奇数个引号结尾
    333. if (IfOddEndQuota(dataArray[i]))
    334. {
    335. colAL.Add(GetHandleData(cellData));
    336. oddStartQuota = false;
    337. continue;
    338. }
    339. }
    340. else
    341. {
    342. //是否以奇数个引号开始
    343. if (IfOddStartQuota(dataArray[i]))
    344. {
    345. //是否以奇数个引号结尾,不能是一个双引号,并且不是奇数个引号
    346. if (IfOddEndQuota(dataArray[i]) && dataArray[i].Length > 2 && !IfOddQuota(dataArray[i]))
    347. {
    348. colAL.Add(GetHandleData(dataArray[i]));
    349. oddStartQuota = false;
    350. continue;
    351. }
    352. else
    353. {
    354. oddStartQuota = true;
    355. cellData = dataArray[i];
    356. continue;
    357. }
    358. }
    359. else
    360. {
    361. colAL.Add(GetHandleData(dataArray[i]));
    362. }
    363. }
    364. }
    365. if (oddStartQuota)
    366. {
    367. throw new Exception("数据格式有问题");
    368. }
    369. this.rowAL.Add(colAL);
    370. }
    371. ///
    372. /// 去掉格子的首尾引号,把双引号变成单引号
    373. ///
    374. ///
    375. ///
    376. private string GetHandleData(string fileCellData)
    377. {
    378. if (fileCellData == "")
    379. {
    380. return "";
    381. }
    382. if (IfOddStartQuota(fileCellData))
    383. {
    384. if (IfOddEndQuota(fileCellData))
    385. {
    386. return fileCellData.Substring(1,fileCellData.Length-2).Replace("\"\"","\""); //去掉首尾引号,然后把双引号变成单引号
    387. }
    388. else
    389. {
    390. throw new Exception("数据引号无法匹配" + fileCellData);
    391. }
    392. }
    393. else
    394. {
    395. //考虑形如"" """" """"""
    396. if (fileCellData.Length >2 && fileCellData[0] == '\"')
    397. {
    398. fileCellData = fileCellData.Substring(1,fileCellData.Length-2).Replace("\"\"","\""); //去掉首尾引号,然后把双引号变成单引号
    399. }
    400. }
    401. return fileCellData;
    402. }
    403. }

     GameConfigDataBase.cs   通用数据读取管理模板

    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System;
    5. using System.Reflection;
    6. ///
    7. /// csv 通用数据读取管理模板
    8. ///
    9. public class GameConfigDataBase
    10. {
    11. protected virtual string getFilePath ()
    12. {
    13. return "";
    14. }
    15. //PetConfigData
    16. static Dictionarystring,GameConfigDataBase>> dataDic = new Dictionarystring, GameConfigDataBase>> ();
    17. public static T GetConfigData<T> (object key) where T:GameConfigDataBase
    18. {
    19. Type setT = typeof(T);
    20. if (!dataDic.ContainsKey (setT)) {
    21. ReadConfigData ();
    22. }
    23. Dictionary<string,GameConfigDataBase> objDic = dataDic [setT];
    24. Debug.Log("test (" + key + ")" + objDic.Count);
    25. if (!objDic.ContainsKey (key.ToString())) {
    26. throw new Exception ("no this config");
    27. }
    28. return (T)(objDic [key.ToString()]);
    29. }
    30. public static List<T> GetConfigDatas<T> () where T:GameConfigDataBase
    31. {
    32. List returnList = new List ();
    33. Type setT = typeof(T);
    34. if (!dataDic.ContainsKey (setT)) {
    35. ReadConfigData ();
    36. }
    37. Dictionary<string,GameConfigDataBase> objDic = dataDic [setT];
    38. foreach (KeyValuePair<string,GameConfigDataBase> kvp in objDic) {
    39. returnList.Add ((T)(kvp.Value));
    40. }
    41. return returnList;
    42. }
    43. static void ReadConfigData<T> () where T:GameConfigDataBase
    44. {
    45. T obj = Activator.CreateInstance ();
    46. string fileName = obj.getFilePath ();
    47. string getString = Resources.Load("GameConfig/" + fileName).text;
    48. CsvReaderByString csr = new CsvReaderByString (getString);
    49. Dictionary<string,GameConfigDataBase> objDic = new Dictionary<string, GameConfigDataBase> ();
    50. FieldInfo[] fis = new FieldInfo[csr.ColCount];
    51. for (int colNum=1; colNum1; colNum++) {
    52. fis [colNum - 1] = typeof(T).GetField (csr [1, colNum]);
    53. }
    54. for (int rowNum=3; rowNum1; rowNum++) {
    55. T configObj = Activator.CreateInstance ();
    56. for (int i=0; i
    57. string fieldValue = csr [rowNum, i + 1];
    58. object setValue = new object ();
    59. switch (fis [i].FieldType.ToString ()) {
    60. case "System.Int32":
    61. setValue = int.Parse (fieldValue);
    62. break;
    63. case "System.Int64":
    64. setValue = long.Parse (fieldValue);
    65. break;
    66. case "System.String":
    67. setValue = fieldValue;
    68. break;
    69. default:
    70. Debug.Log ("error data type");
    71. break;
    72. }
    73. fis [i].SetValue (configObj, setValue);
    74. if (fis [i].Name == "key" || fis [i].Name == "id") {
    75. //只检测key和id的值,然后添加到objDic 中
    76. objDic.Add (setValue.ToString (), configObj);
    77. }
    78. }
    79. }
    80. dataDic.Add (typeof(T), objDic); //可以作为参数
    81. }
    82. }

    读取示例

            //数组读取
            var level_configs = LevelConfig.GetConfigDatas();

            //单条读取
            var pet = LevelConfig.GetConfigData(1);
            var pet2 = LevelConfig.GetConfigData("1");

  • 相关阅读:
    SQL LIKE 运算符
    几分钟上线一个项目文档网站,这款开源神器实在太香了~
    Educational Codeforces Round 148 [Rated for Div. 2]A~C
    一文整明白Researcher ID与ORCID
    [数据结构] 串与KMP算法详解
    iOS 面向对象与类
    深入剖析Spring框架:循环依赖的解决机制
    Oracle数据库----第七周实验____循环与游标
    揭秘108个CMD命令,让你成为计算机大神
    【opencv图像处理】-- 7. 图像金字塔与直方图
  • 原文地址:https://blog.csdn.net/weixin_41843959/article/details/126059817