Unity读取保存CSV(XML)文件

Unity读取保存CSV(XML)文件

创建CSV文件

在Unity的StreamingAssets文件夹下,创建Excel表格,并输入相应数据。
例如:
|  |  ||--|--||  |  |
注意:格式会影响到代码的解析,大家可以根据自己喜欢的格式对表格和代码进行相应的更改。
在Excel中输入相应的数据后,将文件另存为CSV类型的文件。这里必须是另存为

读取与保存

using System.Collections.Generic;
using UnityEngine;
using System.IO;

/// <summary>
/// CSV(XML)的数据管理者
/// </summary>
public abstract class CsvDataManager<T> : Singleton<T>
    where T : CsvDataManager<T>
{
    protected CsvDataManager(string filename, int interval = 0) : base()
    {
        m_ExlceFileName = filename;
        m_Interval = interval;
        ReadData(ReadSteam());
    }

    /// <summary>
    /// 开头的间隔
    /// </summary>
    protected int m_Interval = 0;
    /// <summary>
    /// 表格(XML、CSV)文件名字
    /// </summary>
    protected string m_ExlceFileName = "";
    protected int m_Count = -1;
    /// <summary>
    /// 数据数量
    /// </summary>
    public int Count { get => m_Count; }
    /// <summary>
    /// 标题名字
    /// </summary>
    protected Dictionary<string, int> m_TitleName = new Dictionary<string, int>();
    /// <summary>
    /// 数据链表数组
    /// </summary>
    protected List<string[]> m_DataListArr = new List<string[]>();

    /// <summary>
    /// 获得文件路径
    /// </summary>
    /// <param name="filename">文件名字</param>
    /// <returns>文件在应用中的路径</returns>
    public static string GetFilePath(string filename)
    {
        string filePath = filename;
#if WINDOWS || UNITY_EDITOR
        filePath = Application.dataPath + "/StreamingAssets/CSV/" + filePath;
#elif IPHONE
            filePath = Application.dataPath +"/Raw/CSV/"+ filePath;
#elif ANDROID
            filePath = Application.streamingAssetsPath + "/CSV/" + filePath;
#endif
        //Debug.Log(filePath);
        return filePath;
    }

    /// <summary>
    /// 读取文件流
    /// </summary>
    /// <returns>返回的数据流</returns>
    protected StreamReader ReadSteam()
    {
        m_Count = 0;
        m_TitleName.Clear();
        m_DataListArr.Clear();
        if (string.IsNullOrEmpty(m_ExlceFileName)) return null;
        string path = GetFilePath(m_ExlceFileName);
        //string content = File.ReadAllText(path, System.Text.Encoding.Default);
        //File.WriteAllText(path, content, System.Text.Encoding.UTF8);
        FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
#if UNITY_EDITOR
        return new StreamReader(fs, System.Text.Encoding.Default);
#elif WINDOWS
        return new StreamReader(fs, System.Text.Encoding.UTF8);
#elif ANDROID
        return new StreamReader(fs, System.Text.Encoding.UTF8);
#elif IPHONE
        return new StreamReader(fs, System.Text.Encoding.UTF8);
#endif
    }

    /// <summary>
    /// 读取文件数据
    /// </summary>
    protected virtual void ReadData(StreamReader sr)
    {
        string str = ""; Debug.Log(sr.ReadLine());
        for (; (str = sr.ReadLine()) != null; m_Count++)
        {
            if (m_Interval > m_Count)
            {//开头可能会有的间隔
                continue;
            }
            else if (m_Interval == m_Count)
            {//标题
                string[] arr = str.Split(',');
                for (int i = 0; i < arr.Length; i++)
                {
                    m_TitleName[arr[i]] = i; //Debug.Log(arr[i]);
                }
            }
            else
            {
                m_DataListArr.Add(str.Split(',')); //Debug.Log(str);
            }
        }
        //Debug.Log("111");
        sr.Close();
    }
    
    /// <summary>
    /// 保存数据
    /// </summary>
    public virtual void SaveData()
    {
        if (string.IsNullOrEmpty(m_ExlceFileName)) return;
        string path = GetFilePath(m_ExlceFileName);
        if (File.Exists(path))
        {//先将源文件删除
            File.Delete(path);
        }
        StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8);
        for (int i = 0; i < m_TitleArr.Length; i++)
        {
            sw.Write(m_TitleArr[i] + ',');
        }
        sw.Write("\r\n");
        for (int i = 0; i < m_DataListArr.Count; i++)
        {
            for (int j = 0; j < m_DataListArr[i].Length; j++)
            {
                sw.Write(m_DataListArr[i][j] + ',');
            }
            sw.Write("\r\n");
        }
        sw.Flush();
        sw.Close();
    }
}

这里虽然做了平台判断,但其实IOS普通情况下,比无法解析CSV文件。
脚本中都有较为详细的注释,我就不做多余赘述了。继承该类之后就可以用了。

Singleton<T>单例

注意:
函数ReadData中
例如:这里是第一行为序号,第二行数据标题,第三行开始为正式数据

if (0 == m_Count)
{
    continue;
}
else if (1 == m_Count)
{
    string[] arr = str.Split(',');
    for (int i = 0; i < arr.Length; i++)
    {
    	m_TitleName[arr[i]] = i;
    	//Debug.Log(arr[i]);
    }
}
else
{
    m_DataListArr.Add(str.Split(','));
    //Debug.Log(str);
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天富儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值