转载请注明出处:http://www.cnblogs.com/U-tansuo/archive/2012/07/11/U_tansuo.html
纠正一点错误(注意看一下红字部分) UnitySendMessage回调unity中的函数,但是这个回调需要一定的时间响应,假如在UnitySendMessage后面立即 UnityPause(true);就会导致unity程序立即暂停,引发回调的函数未被执行。所以采用 [self performSelector:@selector(waitSaveData) withObject:nil afterDelay:1]; 延迟1秒钟在调用暂停可以确保数据保存
双击Home键退出程序调用此函数 实现数据保存
- (void) applicationWillResignActive:(UIApplication*)application {printf_console("-> applicationDidResignActive()\n");UnitySendMessage("data", "SaveDataIOS", @"AchievementData.txt".UTF8String);//新添加代码回调unity中data物体上的SaveDataIOS函数 SaveDataIOS函数实现文件保存[self performSelector:@selector(waitSaveData) withObject:nil afterDelay:1];_didResignActive = YES; }-(void)waitSaveData{UnityPause(true); }
双击Home 启动应用程序进入此函数 读取数据
- (void) applicationDidBecomeActive:(UIApplication*)application {printf_console("-> applicationDidBecomeActive()\n");if (_didResignActive){UnityPause(false);UnitySendMessage("data", "ReadDataIOS", @"data.txt".UTF8String);//新添加代码回调unity中data物体上的ReadDataIOS函数 ReadDataIOS函数实现文件读取 } }
辅助函数 获取路径
public string JsonPath{get{ string path=null;if(Application.platform==RuntimePlatform.IPhonePlayer){path= Application.dataPath.Substring (0, Application.dataPath.Length - 5);path = path.Substring(0, path.LastIndexOf('/'))+"/Documents/"; }
else if(Application.platform==RuntimePlatform.Android)
{
path= Application.persistentDataPath+"/";
}else{path=Application.dataPath+"/Resource/GameData/";}return path;} }
根据平台 获取存放文件路径 为ios设备存储到Documents文件夹下
读文件:
public void LoadDataWithFile(string txtName){string path=JsonPath+txtName;if(File.Exists(path)){FileStream fs=new FileStream(path,FileMode.Open);StreamReader sr=new StreamReader(fs);FileData = JsonMapper.ToObject(sr.ReadToEnd());sr.Close();fs.Close();}else{Debug.Log("No json ");} }
写文件
public void WriteDataWithFile(string txtName,string content){string path=JsonPath+txtName;FileStream fs;if(!File.Exists(path)){fs=new FileStream(path,FileMode.Create);}else{fs=new FileStream(path,FileMode.Truncate);//注意对存在文件内容替换 }StreamWriter sw=new StreamWriter(fs);sw.Write(content);sw.Close();fs.Close(); }