本次我们要使用C#的方式进行txt文件的读取和写入,在Unity的开发过程中同样适用,下面来具体实现吧。
创建文件的打开、关闭、读取、写入类:MyFileStream
要引入System.IO和System.Runtime.Serialization.Formatters.Binary和,一个是文件读取的IO类和另一个是二进制类,具体代码如下:
[AppleScript] 纯文本查看 复制代码
using UnityEngine; using System.Collections; using System.Runtime.Serialization.Formatters.Binary; using System.IO; public class MyFileStream { FileStream file; StreamReader st; StreamWriter sw; public bool Open(string FileName, FileAccess Mode) { bool Success = false; string path = PathForDocumentsFile(FileName); if (Mode == FileAccess.Read) { if (File.Exists(path)) { file = new FileStream(path, FileMode.Open, FileAccess.Read); if (file != null) { st = new StreamReader(file); Success = true; } } } else if (Mode == FileAccess.Write) { file = new FileStream(path, FileMode.Create, FileAccess.Write); if (file != null) { sw = new StreamWriter(file); Success = true; } } return Success; } public string ReadLine() { return st.ReadLine(); } public void WriteLine(string Line) { sw.WriteLine(Line); } public void Close() { if( st != null ) { st.Close(); st = null; } if (sw != null) { sw.Close(); sw = null; } if( file != null ) { file.Close(); file = null; } } public string PathForDocumentsFile(string filename) { //暂时只判断安卓和PC if (Application.platform == RuntimePlatform.Android) { string path = Application.persistentDataPath; path = path.Substring(0, path.LastIndexOf('/')); return Path.Combine(path, filename); } else { string path = Application.dataPath; path = path.Substring(0, path.LastIndexOf('/')); return Path.Combine(path, filename); } } }
创建需要保存的文件和字段具体调用类:MyLocalData
[AppleScript] 纯文本查看 复制代码
using UnityEngine; using System.Collections; public class MyLocalData : MonoBehaviour { public static MyLocalData Instance() { if (_instance == null) { _instance = new MyLocalData(); } return _instance; } public class MyLocalSaveData { public int test01; public int test02; public int test03; } public MyLocalSaveData m_Data = new MyLocalSaveData(); MyFileStream m_FS = new MyFileStream(); string m_FileName = "LocalSaveData.txt"; public void InitLoad() { if (m_FS.Open(m_FileName, System.IO.FileAccess.Read)) { m_Data.test01 = 0; m_Data.test02 = 0; m_Data.test03 = 0; int Num = 0; if(int.TryParse(m_FS.ReadLine() , out Num)) { m_Data.test01 = Num; } if(int.TryParse(m_FS.ReadLine() , out Num)) { m_Data.test02 = Num; } if(int.TryParse(m_FS.ReadLine() , out Num)) { m_Data.test03 = Num; } m_FS.Close(); } } public void Write() { if (m_FS.Open(m_FileName, System.IO.FileAccess.Write)) { m_FS.WriteLine(m_Data.test01.ToString()); m_FS.WriteLine(m_Data.test02.ToString()); m_FS.WriteLine(m_Data.test03.ToString()); m_FS.Close(); } } } 可以把MyLocalData类挂载在场景中的一个GameObject上,然后需要调用进行读取写入就是如下代码即可,读取: MyLocalData.Instance().m_Data.test01;写入: MyLocalData.Instance().m_Data.test01 = 1; MyLocalData.Instance().Write();
Ricky Yang个人原创,版权所有,转载注明,谢谢。http://blog.csdn.net/yangy
泰斗原文:http://www.taidous.com/thread-32688-1-1.html?_dsign=7fad4c27