1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 using System.IO; 5 using System.Runtime.Serialization.Formatters.Binary;//重点 6 7 public class GameSaveManager : MonoBehaviour 8 { 9 public Inventory myInventory;//需要保存的数据 10 public Item HpMedicine;//需要保存的数据 11 public Item MpMedicine;//需要保存的数据 12 13 public void SaveGame() //保存游戏方法 14 { 15 Debug.Log(Application.persistentDataPath); 16 //Debug.Log(12); 17 if (!Directory.Exists(Application.persistentDataPath + "/game_SaveGame")) 18 { 19 //Debug.Log(13); 20 Directory.CreateDirectory(Application.persistentDataPath + "/game_SaveGame"); 21 } 22 23 BinaryFormatter formatter = new BinaryFormatter();//二进制转换 24 25 FileStream file = File.Create(Application.persistentDataPath + "/game_SaveGame/Inventory.txt"); 26 27 var json0 = JsonUtility.ToJson(myInventory);//需要保存的数据Json转换 28 var json1 = JsonUtility.ToJson(HpMedicine);//需要保存的数据Json转换 29 var json2 = JsonUtility.ToJson(MpMedicine);//需要保存的数据Json转换 30 31 formatter.Serialize(file, json0);//保存的数据 32 formatter.Serialize(file, json1);//保存的数据 33 formatter.Serialize(file, json2);//保存的数据 34 35 file.Close(); 36 } 37 public void LoadGame()//读取游戏方法 38 { 39 BinaryFormatter bf = new BinaryFormatter(); 40 41 if (File.Exists(Application.persistentDataPath + "/game_SaveGame/Inventory.txt")) 42 { 43 FileStream file = File.Open(Application.persistentDataPath + "/game_SaveGame/Inventory.txt", FileMode.Open); 44 45 JsonUtility.FromJsonOverwrite((string)bf.Deserialize(file), myInventory);//保存的数据 46 JsonUtility.FromJsonOverwrite((string)bf.Deserialize(file), HpMedicine);//保存的数据 47 JsonUtility.FromJsonOverwrite((string)bf.Deserialize(file), MpMedicine);//保存的数据 48 49 file.Close(); 50 } 51 52 } 53 public void ExitGame()//退出游戏方法 54 { 55 56 } 57 58 59 }