UIFramework之数据表读取工具

来源:互联网 发布:孕五个月胎动知男女 编辑:程序博客网 时间:2024/06/11 11:02

UIFramework之数据表读取工具

常见数据表配置文件,有使用xml,excel,csv,Jason等等。其实大概思路都一样,都是先读取文件,把数据以某种数据结构的形式存在于代码中。Unity中的数据,我们以Prefab的形式保存下来,需要使用的相关数据时,通过加载Prefab并实例化,来读取Prefab上保存的相关数据即可。下面我们以读取csv文件中的数据为示例:

定义CSV文件读取工具方法:

[csharp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /* 
  2. * Name: CSVReader.cs 
  3. * Function: N/A  
  4.  
  5. * Ver     变更日期               负责人                            变更内容 
  6. * ────────────────────────────────────────────────────────────────────── 
  7. * V1.0.0  2016/12/26    http://blog.csdn.net/husheng0      
  8.  
  9. * Copyright (c). All rights reserved. 
  10. */  
  11. using UnityEngine;  
  12. using System.Collections;  
  13. using System;  
  14. using System.IO;  
  15. using System.Text;  
  16. using System.Collections.Generic;  
  17.   
  18.   
  19. /// <summary>  
  20. /// CSV格式文件读取器,把csv文件数据全部读取到List  
  21. ///   
  22. ///   
  23. /// #编号|属性1|属性2  
  24. /// Id|IntValue|StrValue  
  25. /// 1|100|string1  
  26. /// 2|200|string2  
  27. /// </summary>  
  28. public class CSVReader  
  29. {  
  30.     //读取文件存在形式  
  31.     public List<List<string>> ContentList = new List<List<string>>();  
  32.     //读取的文件路径  
  33.     public string CSVFileName;  
  34.     /// <summary>  
  35.     /// 读取CSV文件,保存至ContentList  
  36.     /// </summary>  
  37.     /// <param name="fileName">文件路径</param>  
  38.     public void LoadCSVFile(String fileName)  
  39.     {  
  40.         CSVFileName = fileName;  
  41.         //清空数据  
  42.         ContentList.Clear();  
  43.         try  
  44.         {  
  45.             FileStream fs = new FileStream(fileName, FileMode.Open,   
  46.                 FileAccess.Read, FileShare.ReadWrite);  
  47.             StreamReader reader = new StreamReader(fs, Encoding.UTF8);  
  48.             string content = reader.ReadToEnd();  
  49.             LoadCSVFileContent(content);  
  50.             reader.Close();  
  51.             fs.Close();  
  52.         }  
  53.         catch (Exception e)  
  54.         {  
  55.             Debug.LogException(e);  
  56.         }  
  57.     }  
  58.     /// <summary>  
  59.     /// 转化一行数据保存至List  
  60.     /// </summary>  
  61.     /// <param name="content">一行数据的字符串</param>  
  62.     public void LoadCSVFileContent(String content)  
  63.     {  
  64.         StringReader sr = new StringReader(content);  
  65.   
  66.         string line = null;  
  67.   
  68.         while ((line = sr.ReadLine()) != null)  
  69.         {  
  70.             line = line.Trim(' ''\t');  
  71.             if (line == ""continue;  
  72.   
  73.             List<string> items = new List<string>();  
  74.             items.AddRange(line.Split('|'));  
  75.             for (int i = 0; i < items.Count; i++) items[i].Trim(' ''\t');  
  76.             ContentList.Add(items);  
  77.         }  
  78.         sr.Close();  
  79.     }  
  80.      
  81.     /// <summary>  
  82.     /// 报错  
  83.     /// </summary>  
  84.     /// <param name="row">行数</param>  
  85.     /// <param name="col">列数</param>  
  86.     void LogError(int row, int col)  
  87.     {  
  88.         if (row - 1 >= ContentList.Count)  
  89.             Debug.LogError("Import Data Error At Row " + row + " Col " + col);  
  90.         else  
  91.         {  
  92.             if (col - 1 >= ContentList[row - 1].Count)  
  93.                 Debug.LogError("Import Data Error At Row " + row + " Col " + col);  
  94.         }  
  95.     }  
  96. }  

定义读取CSV文件的对应Prefab脚本父类:

[csharp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. using System;  
  2. using UnityEngine;  
  3. using System.Collections.Generic;  
  4. using System.Reflection;  
  5. using Debug = UnityEngine.Debug;  
  6.   
  7. /// <summary>  
  8. /// 实现自动读取CSV的Prefab脚本基类  
  9. /// </summary>  
  10. public class ImportDatabase : MonoBehaviour  
  11. {  
  12.     public List<List<string>> ContentList = new List<List<string>>();  
  13.   
  14.     private string FileName;  
  15.     /// <summary>  
  16.     /// 导入数据  
  17.     /// </summary>  
  18.     public void ImportData(CSVReader reader)  
  19.     {  
  20.         ClearData();  
  21.         FileName = reader.CSVFileName;  
  22.         Debug.Log("Start Import CSVFile:" + FileName);  
  23.         Import2CSVFinished();  
  24.         if (reader.ContentList.Count > 2)  
  25.         {  
  26.             for (int i = 2; i < reader.ContentList.Count; i++)  
  27.             {  
  28.                 ContentList.Add(reader.ContentList[i]);  
  29.             }  
  30.         }  
  31.         else  
  32.         {  
  33.             Debug.LogError("CSVFile:" + FileName + "Data Empty!");  
  34.             return;  
  35.         }  
  36.         ImportDataInit();  
  37.         Import2PrefabFinished();  
  38.         Debug.Log("Complete Import CSVFile:" + FileName);  
  39.     }  
  40.     /// <summary>  
  41.     /// 清除数据  
  42.     /// </summary>  
  43.     public virtual void ClearData()  
  44.     {  
  45.         ContentList.Clear();  
  46.     }  
  47.     /// <summary>  
  48.     /// 初始化数据到Perfab  
  49.     /// </summary>  
  50.     public virtual void ImportDataInit()  
  51.     {  
  52.     }  
  53.     /// <summary>  
  54.     /// 数据导入Prefab结束后的处理  
  55.     /// </summary>  
  56.     public virtual void Import2PrefabFinished()  
  57.     {  
  58.     }  
  59.     /// <summary>  
  60.     /// 数据导入CSV文件结束后的处理  
  61.     /// </summary>  
  62.     public virtual void Import2CSVFinished()  
  63.     {  
  64.     }  
  65. }  


示例Prefab文件:

[csharp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. using UnityEngine;  
  2. using System;  
  3. using System.Collections;  
  4. using System.Collections.Generic;  
  5. /// <summary>  
  6. /// 示例  
  7. /// </summary>  
  8. public class ExampleDB : ImportDatabase  
  9. {  
  10.     public static ExampleDB Instance = null;  
  11.   
  12.     void Awake()  
  13.     {  
  14.         if (null == Instance)  
  15.         {  
  16.             Instance = this//调用构造函数    
  17.         }  
  18.     }  
  19.   
  20.     void OnDestroy()  
  21.     {  
  22.         Instance = null;  
  23.     }  
  24.     [SerializeField]  
  25.     public List<ExampleData> ExampleDataList = new List<ExampleData>();  
  26.   
  27.     public override void ImportDataInit()  
  28.     {  
  29.         base.ImportDataInit();  
  30.         for (int i = 0; i < base.ContentList.Count; i++)  
  31.         {  
  32.             List<string> tempList = base.ContentList[i];  
  33.   
  34.             ExampleDataList.Add(new ExampleData  
  35.             {  
  36.                 Id = int.Parse(tempList[0]),  
  37.                 IntValue = int.Parse(tempList[1]),  
  38.                 StrValue = tempList[2]  
  39.             });  
  40.         }  
  41.     }  
  42.   
  43.     public override void ClearData()  
  44.     {  
  45.         base.ClearData();  
  46.         ExampleDataList.Clear();  
  47.     }  
  48. }  
  49.   
  50. [Serializable]  
  51. public class ExampleData  
  52. {  
  53.     public int Id;  
  54.     public int IntValue;  
  55.     public string StrValue;  
  56. }  

导入文件方法,简单点说就是把Prefab加载到Hierarchy目录->导入数据->替换原Prefab文件:

[csharp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. using System;  
  2. using UnityEngine;  
  3. using UnityEditor;  
  4. using System.Collections.Generic;  
  5. using System.IO;  
  6. using Object = UnityEngine.Object;  
  7.   
  8. public class CSVFile2PrefabTools  
  9. {  
  10.     //预设文件所在的根目录  
  11.     public const string PrefabPath =   
  12.         "Assets/Resources/Prefabs/Databases/ExampleDB.prefab";  
  13.     //CSV文件所在的根目录  
  14.     public static string CSVPath =   
  15.         Application.dataPath + "/../Datas/ExampleData.csv";  
  16.   
  17.     /// <summary>  
  18.     /// 基于配置的prefab自动导入csv功能  
  19.     /// </summary>  
  20.     [MenuItem("Custom/PrefabTools/CSVFile2Prefab")]  
  21.     public static void CSVFile2Prefab()  
  22.     {  
  23.         ImportDatabase TempDataPrefab = null;  
  24.         try  
  25.         {  
  26.             GameObject prefab = AssetDatabase.LoadAssetAtPath(PrefabPath,  
  27.                 typeof(GameObject)) as GameObject;  
  28.   
  29.             GameObject TargetDataPrefab = null;  
  30.             if (prefab != null)  
  31.             {  
  32.                 TargetDataPrefab = PrefabUtility.InstantiatePrefab(prefab) as GameObject;  
  33.                 TempDataPrefab = TargetDataPrefab.GetComponent<ImportDatabase>();  
  34.                 if (TempDataPrefab != null)  
  35.                 {  
  36.                     CSVReader tempCSV = new CSVReader();  
  37.                     tempCSV.LoadCSVFile(CSVPath);  
  38.                     TempDataPrefab.ImportData(tempCSV);  
  39.                     PrefabUtility.ReplacePrefab(TargetDataPrefab, prefab);  
  40.                     GameObject.DestroyImmediate(TargetDataPrefab);  
  41.                 }  
  42.             }  
  43.             else  
  44.             {  
  45.                 Debug.LogError(PrefabPath + " Is Load Failure!");  
  46.             }  
  47.         }  
  48.         catch (Exception exp)  
  49.         {  
  50.             Debug.LogError(exp.Message);  
  51.             Debug.LogError(exp.StackTrace);  
  52.   
  53.             if (exp.InnerException != null)  
  54.             {  
  55.                 Debug.LogError(exp.InnerException.Message);  
  56.                 Debug.LogError(exp.InnerException.StackTrace);  
  57.             }  
  58.         }  
  59.         //保存场景  
  60.         EditorApplication.SaveScene();  
  61.     }  
  62. }  

[csharp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. using UnityEngine;  
  2. using System.Collections;  
  3. #if UNITY_EDITOR  
  4. using UnityEditor;  
  5. #endif  
  6.   
  7. /// <summary>  
  8. /// 为Prefab预设添加单个导入操作  
  9. /// </summary>  
  10. public abstract class BaseDBEditor : Editor  
  11. {  
  12.     private ImportDatabase DataBase;  
  13.   
  14.     void OnEnable()  
  15.     {  
  16.         DataBase = target as ImportDatabase;  
  17.     }  
  18.     public override void OnInspectorGUI()  
  19.     {  
  20.         GUILayout.BeginHorizontal();  
  21.         if (GUILayout.Button("ImportData", GUILayout.Width(80f)))  
  22.         {  
  23.             string dataPath = EditorUtility.OpenFilePanel("Select a CSVFile""""csv");  
  24.             if (!dataPath.Contains(".csv")) return;  
  25.             ImportData(dataPath);  
  26.             Debug.Log("CSVFilePath" + dataPath);  
  27.         }  
  28.         GUILayout.EndHorizontal();  
  29.         DrawDefaultInspector();  
  30.     }  
  31.   
  32.     private void ImportData(string fileName)  
  33.     {  
  34.         CSVReader tempCSV = new CSVReader();  
  35.         tempCSV.LoadCSVFile(fileName);  
  36.         DataBase.ImportData(tempCSV);  
  37.     }  
  38. }  
  39.   
  40. /// <summary>  
  41. /// ExampleDB  
  42. /// </summary>  
  43. [CustomEditor(typeof(ExampleDB))]  
  44. public class ExampleDBEditor : BaseDBEditor  
  45. {  
  46. }  

[csharp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. using UnityEngine;  
  2. using System.Collections;  
  3. /// <summary>  
  4. /// 测试文件  
  5. /// </summary>  
  6. public class Test : MonoBehaviour  
  7. {  
  8.   
  9.     UnityEngine.Object obj = null;  
  10.     GameObject go = null;  
  11.     void Awake()  
  12.     {  
  13.         obj = Resources.Load("Prefabs/Databases/ExampleDB");  
  14.         if (null == obj)  
  15.         {  
  16.             return;  
  17.         }  
  18.         else  
  19.         {  
  20.             Debug.LogError("--->Load success");  
  21.             go = GameObject.Instantiate(obj) as GameObject;  
  22.             go.SetActive(true);  
  23.   
  24.             if (null == ExampleDB.Instance) return;  
  25.             foreach (ExampleData temp in ExampleDB.Instance.ExampleDataList)  
  26.             {  
  27.                 Debug.LogError(temp.Id + "-->" + temp.IntValue + "-->" + temp.StrValue);  
  28.             }  
  29.         }  
  30.     }  
  31.   
  32.     void OnDisable()  
  33.     {  
  34.         if (null != go) Object.Destroy(go);  
  35.     }  
  36. }  

测试结果:


====================================================================

结束。


0 0
原创粉丝点击