笔者介绍:姜雪伟,IT公司技术合伙人,IT高级讲师,CSDN社区专家,特邀编辑,畅销书作者,已出版书籍:《手把手教你架构3D游戏引擎》电子工业出版社和《Unity3D实战核心技术详解》电子工业出版社等。
CSDN视频网址:http://edu.csdn.net/lecturer/144
游戏开发中经常涉及到文本文件的加载处理,游戏常用文件格式非常多,json,xml,csv,二进制等等,在这里给读者封装的是csv文件的加载,其实,在游戏中使用csv文件格式就是将excel另存为csv格式即可,这样非常方便策划对配置文件的修改。配置文件的处理有很多种方式,在这里给读者推荐一种比较简单的加载脚本,代码如下所示:
using System;
using System.Collections;
using System.Collections.Generic;
namespace Utils
{
public class CsvReader
{
//
// Properties
//
public int ColCount
{
get
{
return m_Col;
}
}
protected List<string[]> Datas
{
get
{
if (m_Datas == null)
{
m_Datas = new List<string[]>();
}
return m_Datas;
}
}
public int RowCount
{
get
{
if (m_Datas == null)
{
return 0;
}
return m_Datas.Count;
}
}
//
// Methods
//
public void Clear()
{
if (m_Datas != null)
{
m_Datas.Clear();
}
m_Col = 0;
}
public bool GetBoolData(int r, int c)
{
return GetIntData(r, c) != 0;
}
public string GetData(int r, int c)
{
if (m_Datas == null)
{
return string.Empty;
}
if (r < 0 || r >= m_Datas.Count)
{
return string.Empty;
}
if (c < 0 || c >= m_Datas[r].Length)
{
return string.Empty;
}
return m_Datas[r][c].Trim();
}
public float GetFloatData(int r, int c)
{
string data = GetData(r, c);
if (string.IsNullOrEmpty(data))
{
return 0f;
}
float result;
if (!float.TryParse(data, out result))
{
result = 0f;
}
return result;
}
public int GetIntData(int r, int c)
{
string data = GetData(r, c);
if (string.IsNullOrEmpty(data))
{
return 0;
}
int result;
if (!int.TryParse(data, out result))
{
result = 0;
}
return result;
}
public bool LoadFromFile(string fileName)
{
string text = Singleton<ResourceMgr>.Instance.LoadText(fileName, ResourceCacheType.rctNone);
return text != null && LoadFromString(text);
}
public bool LoadFromString(string text)
{
Clear();
if (string.IsNullOrEmpty(text))
{
return false;
}
string[] array = text.Split(CsvReader._cLineDims);
if (array != null && array.Length > 0)
{
for (int i = 0; i < array.Length; i++)
{
string text2 = array[i];
if (!string.IsNullOrEmpty(text2))
{
string[] array2 = text2.Split(new char[]
{
','
});
Datas.Add(array2);
m_Col = Math.Max(m_Col, array2.Length);
}
}
}
return true;
}
public static readonly char _cLineDims = ';';
private List<string[]> m_Datas = null;
private int m_Col = 0;
// private int m_Row = 0;
}
}
以上代码可以直接在工程中使用,直接掉用接口:
public bool LoadFromFile(string fileName)
脚本中也提供了数据清理,获取数据等接口供用户使用。。。。。。