Unity C# File类 本地数据保存和游戏存档

进行本地数据存档和载入在游戏开发中很是常见,几乎任何一款游戏都须要这样的功能。算法

命名空间:加密

using System.IO;spa

主要用于引入File类以处理各种文件操做。插件

using System.Runtime.Serialization.Formatters.Binary;code

用于对文件进行序列化与反序列化。orm

 

1.判断数据文件是否存在:对象

1     static public bool HasGameSaveData(string fileName) 2  { 3         if (File.Exists(Application.persistentDataPath + "/" + fileName)) 4             return true; 5         else
6             return false; 7     }

主要用到File.Exists(string filePath);方法blog

Application.persistentDataPath是相对路径,用于在不一样的平台都能获得正确的路径游戏

 

2.读(存档载入)游戏开发

 1     static public GameSaveData saveData= new GameSaveData();  2 
 3     static public void LoadGameSaveData(string fileName)  4  {  5         if (!HasGameSaveData(fileName))  6  {  7  NewGameSaveData(fileName);  8  }  9         else
10  { 11             BinaryFormatter bf = new BinaryFormatter(); 12             FileStream file = File.Open(Application.persistentDataPath + "/" + fileName, FileMode.Open); 13             saveData = (GameSaveData)bf.Deserialize(file); 14  file.Close(); 15  } 16     }

GameSaveData也就是游戏中要保存的某个数据类,这里就省略了

读取数据要先判断文件是否存在,没有就新建一个;NewGameSaveData(fileName);中初始化后通常会立马写入(如何写见后面)

读取的过程是将文件打开后反序列化为对应的类型,也就是将二进制文件转化为可直接处理的对象

若是用到了Easy Save插件,也能够这么读取:

 1     static public void LoadGameSaveData(string fileName,string fileKey,string filePassCode)  2  {  3         if (!HasGameSaveData(fileName))  4  {  5  NewGameSaveData(fileName);  6  }  7         else
 8  {  9             var passCodeSet = new ES3Settings(ES3.EncryptionType.AES, filePassCode);//数据加密设置
10             saveData = ES3.Load<GameSaveData>(fileKey, Application.persistentDataPath + "/" + fileName, passCodeSet); 11  } 12     }

Easy Save能够很方便的给文件加密,这里用的第三个版本;其中filePassCode是文件解密的密码,它的后台用的是Rijndael算法

 

3.写(存档)

1     static public void WriteGameSaveData(string fileName) 2  { 3         BinaryFormatter bf = new BinaryFormatter(); 4         FileStream file = File.Create(Application.persistentDataPath + "/" + fileName); 5  bf.Serialize(file, saveData); 6  file.Close(); 7     }

写入文件和读取比较相似,是将对象序列化为二进制文件流;通常一个数据对象在初始化结束后,会自动运行一次写操做,其他时候则根据玩家的交互必要的时候进行写入

一样的,Easy Save的版本以下:

1     static public void WriteGameSaveData(string fileName,string fileKey,string filePassCode) 2  { 3         var passCodeSet = new ES3Settings(ES3.EncryptionType.AES, filePassCode);//设置加密
4         ES3.Save<GameSaveData>(fileKey, Application.persistentDataPath + "/" + fileName, passCodeSet); 5     }

对于同一个文件,读和写的fileName,fileKey,filePassCode应保持一致

 

4.移除

1     static public void RemoveGameSaveData(string fileName) 2  { 3         if (HasGameSaveData(fileName)) 4  { 5             File.Delete(Application.persistentDataPath + "/" + fileName); 6  } 7     }
相关文章
相关标签/搜索