using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
public class Property{
public int m_nEno;
public ColorType m_colorType;
public int m_bStatu;
}
public class InitData : MonoBehaviour
{
public string[] strEquipName = new string[8];
private static string fileAddress;
public static Dictionary<string , Property > m_equipproperty = new Dictionary<string, Property>();
private static int m_score;
void Awake(){
print("read file.");
strEquipName[0] = "huangguang";
strEquipName[1] = "neck";
strEquipName[2] = "tanzi";
strEquipName[3] = "huediejie";
strEquipName[4] = "kuwa01";
strEquipName[5] = "kuwa02";
strEquipName[6] = "kuwa03";
strEquipName[7] = "kuwa04";
m_equipproperty.Clear();
Property pro;
fileAddress = Application.dataPath + "/Resources/initData.dat";
FileInfo fInfo = new FileInfo(fileAddress);
if(!fInfo.Exists){
// initData.dat file is not exist.
print("initData file is not Exist.");
for(int i=0; i<8; i++){
pro = new Property();
pro.m_nEno = 0;
pro.m_colorType = 0;
pro.m_bStatu = 0;
AddEquipProperty(strEquipName[i],pro);
}
m_score = 0;
WriteData();
}
else{
FileStream fs = new FileStream (fileAddress, FileMode.OpenOrCreate, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
//使用StreamReader类来读取文件
sr.BaseStream.Seek (0, SeekOrigin.Begin);
string strLine ="";
for(int i=0; i<8; i++){
pro = new Property();
strLine = sr.ReadLine();
if (strLine != null)
pro.m_nEno = System.Convert.ToInt32(strLine);
strLine = sr.ReadLine();
if (strLine != null)
pro.m_colorType = (ColorType)System.Convert.ToInt32(strLine);
strLine = sr.ReadLine();
if (strLine != null){
pro.m_bStatu = System.Convert.ToInt32(strLine);
}
AddEquipProperty(strEquipName[i], pro);
//print("property count "+m_equipproperty.Count +"--eno"+pro.m_nEno);
}
strLine = sr.ReadLine();
if (strLine != null)
m_score = System.Convert.ToInt32(strLine);
//关闭此StreamReader对象
sr.Close ();
}
}
void Start ()
{
}
void Update ()
{
}
public void AddEquipProperty(string equipName,Property p){
if(m_equipproperty.ContainsKey(equipName)){
m_equipproperty.Remove(equipName);
}
m_equipproperty.Add(equipName,p);
}
public Dictionary<string,Property> GetEquipProperty(){
return m_equipproperty;
}
public void WriteData()
{
FileStream fs = new FileStream (fileAddress, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter (fs);
sw.Flush ();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
string s="";
for(int i=0; i<8; i++){
Property p = m_equipproperty[strEquipName[i]];
s = p.m_nEno.ToString()+"\n"+((int)p.m_colorType).ToString()+"\n"+p.m_bStatu.ToString();
sw.WriteLine(s);
}
sw.WriteLine(m_score.ToString());
print("save init data success.");
sw.Flush ();
sw.Close ();
}
public int GetScore(){
return m_score;
}
public void SetScore(int s){
m_score = s;
}
}
unity3d C#文本读写操作
最新推荐文章于 2023-05-08 10:44:09 发布