Unity-----列表功能实现(数据读取.CSV文件)
记录一下.csv文件在unity中使用
1.文件路径
需要把csv文件放在StreamingAssets这个文件夹中。放在StreamingAssets中二进制文件打包后,Unity会将这些二进制文件放置在对应平台下的路径下。所以根据不同平台,访问的路径是不一样的。所以二进制文件一定要放在StreamingAssets 中。
2.代码实现
(1)定义与.CSV文件对应的类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
//Info数据
[Serializable]
public class InfoData : MonoBehaviour {
public int ID;
public string Name;
public string Sex;
public int Age;
}
(2).CSV文件读取
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using UnityEngine;
public class LocalData {
public static LocalData instance = null;
public static LocalData _Instance
{
get
{
if (null == instance)
{
instance = new LocalData();
}
return instance;
}
}
public string BinSourcesFolder
{
get
{
return Application.streamingAssetsPath + "/SourcesFolder/";
}
}
public Dictionary<int, InfoData> _InfoData = new Dictionary<int, InfoData>();
public void InitInfo()
{
_InfoData.Clear();
string fullFileName = BinSourcesFolder + "Info.csv";
string InfoConfig = LanChange(fullFileName);
InfoConfig = InfoConfig.Replace("\r", "");
InfoConfig = InfoConfig.Replace("\"", "");
string[] infoDatas = InfoConfig.Split('\n');
for(int i = 1; i < infoDatas.Length; i++)
{
if (infoDatas[i] != "")
{
string[] infos = infoDatas[i].Split(',');
InfoData data = new InfoData
{
ID = int.Parse(infos[0]),
Name = infos[1],
Sex = infos[2],
Age = int.Parse(infos[3])
};
_InfoData.Add(data.ID, data);
Debug.Log(data.ID + " " + data.Name + " " + data.Sex + " " + data.Age);
}
}
}
string LanChange(string path)
{
//csv文件打开方式用记事本打开,编码UTF8
Encoding utf = Encoding.GetEncoding("UTF-8");
return File.ReadAllText(path, utf);
}
}
(3)Unity界面显示
在unity布置好UI将ShowInfo.cs挂载(其中Scroll View实现滑动列表功能具体实现后续再具体记录,其中列表内信息展示实现方法:动态加载预制体方法实现)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ShowInfo : MonoBehaviour {
private Transform mUICanvas;
private void Awake()
{
mUICanvas = transform.Find("Scroll View/Viewport/Content");
}
void Start () {
LocalData._Instance.InitInfo(); //获取.CSV文件数据
GameObject infoItem = (GameObject)Resources.Load("InfoDataIteam");
foreach (var item in LocalData._Instance._InfoData.Values)
{
print("xxx");
InfoData infodata = item as InfoData;
Transform ItemObj = Instantiate(infoItem).transform;
ItemObj.transform.SetParent(mUICanvas, false);
ItemObj.Find("TextID").GetComponent<Text>().text = infodata.ID.ToString();
ItemObj.Find("TextName").GetComponent<Text>().text = infodata.Name;
ItemObj.Find("TextSex").GetComponent<Text>().text = infodata.Sex;
ItemObj.Find("TextAge").GetComponent<Text>().text = infodata.Age.ToString();
}
}
}
(5)最终效果图
①创建的.CSV文件
②unity内实现效果图