方法一:
准备工作:(1)将一个.csv的excel文件存放于Assets\Resources\Config文件夹下面(Excel需要存储为.csv格式,测试出来该方法不能有效读出.csv中存在的中文,只适用于表格中全是英文。
///创建一个单例类模板
public class Singletonwhere T:new ()
{
class SingletonCreator
{
internal static readonly T instance = newT();
}
public static T Get()
{
return SingletonCreator.instance;
}
}
///创建一个加载Resources的管理类
public class CorResMgr : MonoBehaviour
{
private Hashtable mResourceTable = new Hashtable();
static CorResMgr inst = null;
public static CorResMgr Get()
{
return inst;
}
private void Awake()
{
inst = this;
DontDestroyOnLoad(gameObject);
}
/// 根据路径在resources下加载资源
public UnityEngine .Object LoadResOnly(string path)
{
Debug.Log("加载-------"+path);
UnityEngine.Object resource = Resources.Load(path);
if(resource ==null)
{
Debug.LogError("res load fail"+path );
return null;
}
return resource;
}
//Resource加载资源(设置类型)
public UnityEngine.Object LoadResource(string path,System.Type tp )
{
UnityEngine.Object res = Resources.Load(path, tp);
if(res==null)
{
Debug.LogError("res load fail" + path);
return null;
}
return res;
}
//释放资源
public void FreeALLResources()
{
mResourceTable.Clear();
Resources.UnloadUnusedAssets();
System.GC.Collect();
}
///创建加载Resources类完毕
///创建一个表的简单类(用来存放信息的类)
public class TestTable
{
public string name;
public int id;
public string password;
public static TestTable Clone(Type type)
{
TestTable tab = type.Assembly.CreateInstance(type.Name) as TestTable;
return tab;
}
}
///创建一个表的简单类完毕
///创建一个表的加载类
public class GameTableMagr : Singleton 《GameTableMagr》
///根据名字和类型加载
dictionary < string, TestTable> gameTable = new dictionary (string, TestTable)();//存放加载信息的表
//查看gameTable中是否有名叫strName的数据
public bool LoadTable(string strName,Type type)
{
if(gameTable .ContainsKey (strName )==true )
{
Debug.Log("Load table is error!Had a file alread");
return false;
}
//根据名字在Resources文件夹下加载
TextAsset o = (TextAsset )CorResMgr.Get().LoadResOnly("Config/" + strName);
if(o ==null )
{
Debug.Log("Load table is error"+strName );
return false;
}
TestTable tab = TestTable.Clone(type);
tab.name = strName;
ReadTable(o.bytes, ref tab);
gameTable.Add(tab.name, tab);
return false;
}
public void ReadTable(byte [] bytes,ref TestTable tab)
{
if(tab==null )
{
return;
}
string strAll = Encoding.UTF8.GetString(bytes);
Debug.Log("" + strAll);
String[] lines = strAll.Split('\n');
int row = 0;
for (int index = 0; index < lines.Length ; index++)
{
String str = lines[index];
string [] array = str.Split(',');
if(array.Length ==0)
{
break ;
}
if(array [0].Length ==0)
{
break;
}
string [] array = str.Split(',');
for (int j = 0; j < array.Length ; j++)
{
string strfiled;
if(j>array .Length )
{
strfiled = string.Empty;
}else
{
strfiled = array[j];
}
try
{
//Trim()删除字符串头部及尾部出现的空格
//如Trim("abcd".ToCharArray())就是删除字符串头部及尾部出现的a或b或c或d字符
gameTable .AddVaule(row, j, strfiled.Trim());
}catch
{
Debug.LogError (string .Format ("LoadTable Error:Table name {0},line {1} row {2}",tab .name ,j,row));
}
}
row++;
}
}
}