纳金网

标题: 关于unity3D ios 退出保存数据 [打印本页]

作者: 王者再临    时间: 2014-8-31 12:11
标题: 关于unity3D ios 退出保存数据
纠正一点错误(注意看一下红字部分)  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", @"AchievementData.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
            {
                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();
            InitData();
        }
        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();  
    }






欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5