使用json存储角色的数据,数据类型
[Serializable] public class SaveGameData { public CharacterInfo characterInfo; public string title; [HideInInspector] public float savePosX; [HideInInspector] public float savePosY; [HideInInspector] public string path; }
保存游戏数据
public static void SavePlayerInfo(CharacterInfo characterInfo,Transform transform,string title) { SaveGameData saveGame = new SaveGameData() { characterInfo = characterInfo, title = saveIndex + "、" + title, savePosX = transform.position.x, savePosY = transform.position.y, path= Application.dataPath + "/Resources/Save/" + saveIndex + ".json" }; string s = JsonConvert.SerializeObject(saveGame); using (FileStream fs = new FileStream(saveGame.path, FileMode.OpenorCreate, FileAccess.Write)) { byte[] b = System.Text.Encoding.UTF8.GetBytes(s); fs.Write(b,0,b.Length); } saveIndex++; }
读取解析数据
static SaveGameData ReadJson(string path) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { byte[] data = new byte[fs.Length]; if (data.Length==0) return null; fs.Read(data, 0, data.Length); byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf }; string dataStr = System.Text.Encoding.UTF8.GetString(data); if (data[0] == bomBuffer[0] && data[1] == bomBuffer[1] && data[2] == bomBuffer[2]) { int copyLength = data.Length - 3; byte[] datanew = new byte[copyLength]; Buffer.Blockcopy(data, 3, datanew, 0, copyLength); dataStr = System.Text.Encoding.UTF8.GetString(datanew); } return JsonConvert.DeserializeObject<SaveGameData>(dataStr); } }
public static void ReadplayerAllInfo() { string[] paths= Directory.GetFiles(rootPath); List<string> validpath = new List<string>(); for (int i = 0; i < paths.Length; i++) { if (paths[i].EndsWith(".json")) { paths[i]=paths[i].Replace("\\", "/"); validpath.Add(paths[i]); } } m_saveInfo = new List<SaveGameData>(); saveIndex = validpath.Count+1; for (int i = 0; i < validpath.Count; i++) { Debug.Log(validpath[i]); SaveGameData loadplayer = ReadJson(validpath[i]); m_saveInfo.Add(loadplayer); } }
清除保存信息
internal static void ClearSave(SaveGameData saveInfo) { m_saveInfo.Remove(saveInfo); string file= Path.GetFileName(saveInfo.path); string path = rootPath + "/" + file; if (File.Exists(path)) { File.Delete(path); } path= rootPath + "/" + file + ".Meta"; if (File.Exists(path)) { File.Delete(path); } }
暂时没考虑数据加密,后面可能会添加上。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。