Unity3D — —存讀檔【轉載】

詳細可參考此篇博文:json

Unity序列化之XML,JSON--------合成與解析

 

簡單例子(SiKi學院教程):app

 1 using System.Collections;  2 using System.Collections.Generic;  3 using UnityEngine;  4 
 5 [System.Serializable]  6 public class Save{  7 
 8     //怪物位置和類型
 9     public List<int> livingTargetPositions = new List<int>(); 10     public List<int> livingMonsterTypes = new List<int>(); 11 
12     //射擊數和分數
13     public int shootNum = 0; 14     public int score = 0; 15 }
Save類--所要存儲的數據
 1 //建立Save對象並存儲當前遊戲狀態信息
 2     private Save CreateSaveGO()  3  {  4         //新建Save對象
 5         Save save = new Save();  6         //遍歷全部的target  7         //若是其中有處於激活狀態的怪物,就把該target的位置信息和激活狀態的怪物的類型添加到List中
 8         foreach (GameObject targetGO in targetGOs)  9  { 10             TargetManager targetManager = targetGO.GetComponent<TargetManager>(); 11             if (targetManager.activeMonster != null) 12  { 13  save.livingTargetPositions.Add(targetManager.targetPosition); 14                 int type = targetManager.activeMonster.GetComponent<MonsterManager>().monsterType; 15  save.livingMonsterTypes.Add(type); 16  } 17  } 18         //把shootNum和score保存在Save對象中
19         save.shootNum = UIManager._instance.shootNum; 20         save.score = UIManager._instance.score; 21         //返回該Save對象
22         return save; 23     }
添加當前遊戲信息
 1     //經過讀檔信息重置咱們的遊戲狀態(分數、激活狀態的怪物)
 2     private void SetGame(Save save)  3  {  4         //先將全部的targrt裏面的怪物清空,並重置全部的計時
 5         foreach(GameObject targetGO in targetGOs)  6  {  7             targetGO.GetComponent<TargetManager>().UpdateMonsters();  8  }  9         //經過反序列化獲得的Save對象中存儲的信息,激活指定的怪物
10         for(int i = 0; i < save.livingTargetPositions.Count; i++) 11  { 12             int position = save.livingTargetPositions[i]; 13             int type = save.livingMonsterTypes[i]; 14             targetGOs[position].GetComponent<TargetManager>().ActivateMonsterByType(type); 15  } 16 
17         //更新UI顯示
18         UIManager._instance.shootNum = save.shootNum; 19         UIManager._instance.score = save.score; 20         //調整爲未暫停狀態
21  UnPause(); 22     }
讀檔時設置信息

存讀檔三種方式:ide

  >二進制:spa

 1 //二進制方法:存檔和讀檔
 2     private void SaveByBin()  3  {  4         //序列化過程(將Save對象轉換爲字節流)  5         //建立Save對象並保存當前遊戲狀態
 6         Save save = CreateSaveGO();  7         //建立一個二進制格式化程序
 8         BinaryFormatter bf = new BinaryFormatter();  9         //建立一個文件流
10         FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile" + "/byBin.txt"); 11         //用二進制格式化程序的序列化方法來序列化Save對象,參數:建立的文件流和須要序列化的對象
12  bf.Serialize(fileStream, save); 13         //關閉流
14  fileStream.Close(); 15         
16 
17         //若是文件存在,則顯示保存成功
18         if (File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt")) 19  { 20             UIManager._instance.ShowMessage("保存成功"); 21  } 22     }
SaveByBinary
 1 private void LoadByBin()  2  {  3         if(File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))  4  {  5             //反序列化過程  6             //建立一個二進制格式化程序
 7             BinaryFormatter bf = new BinaryFormatter();  8             //打開一個文件流
 9             FileStream fileStream = File.Open(Application.dataPath + "/StreamingFile" + "/byBin.txt", FileMode.Open); 10             //調用格式化程序的反序列化方法,將文件流轉換爲一個Save對象
11             Save save = (Save)bf.Deserialize(fileStream); 12             //關閉文件流
13  fileStream.Close(); 14 
15  SetGame(save); 16             UIManager._instance.ShowMessage(""); 17 
18  } 19         else
20  { 21             UIManager._instance.ShowMessage("存檔文件不存在"); 22  } 23     }
LoadByBinary

  >Json.net

 1  //JSON:存檔和讀檔
 2     private void SaveByJson()  3  {  4         Save save = CreateSaveGO();  5         string filePath = Application.dataPath + "/StreamingFile" + "/byJson.json";  6         //利用JsonMapper將save對象轉換爲Json格式的字符串
 7         string saveJsonStr = JsonMapper.ToJson(save);  8         //將這個字符串寫入到文件中  9         //建立一個StreamWriter,並將字符串寫入文件中
10         StreamWriter sw = new StreamWriter(filePath); 11  sw.Write(saveJsonStr); 12         //關閉StreamWriter
13  sw.Close(); 14 
15         UIManager._instance.ShowMessage("保存成功"); 16     }
SaveByJson
 1  private void LoadByJson()  2  {  3         string filePath = Application.dataPath + "/StreamingFile" + "/byJson.json";  4         if(File.Exists(filePath))  5  {  6             //建立一個StreamReader,用來讀取流
 7             StreamReader sr = new StreamReader(filePath);  8             //將讀取到的流賦值給jsonStr
 9             string jsonStr = sr.ReadToEnd(); 10             //關閉
11  sr.Close(); 12 
13             //將字符串jsonStr轉換爲Save對象
14             Save save = JsonMapper.ToObject<Save>(jsonStr); 15  SetGame(save); 16             UIManager._instance.ShowMessage(""); 17  } 18         else
19  { 20             UIManager._instance.ShowMessage("存檔文件不存在"); 21  } 22     }
LoadByJson

  >Xmlcode

 1     //XML:存檔和讀檔
 2     private void SaveByXml()  3  {  4         Save save = CreateSaveGO();  5         //建立XML文件的存儲路徑
 6         string filePath = Application.dataPath + "/StreamingFile" + "/byXML.txt";  7         //建立XML文檔
 8         XmlDocument xmlDoc = new XmlDocument();  9         //建立根節點,即最上層節點
10         XmlElement root = xmlDoc.CreateElement("save"); 11         //設置根節點中的值
12         root.SetAttribute("name", "saveFile1"); 13 
14         //建立XmlElement
15  XmlElement target; 16  XmlElement targetPosition; 17  XmlElement monsterType; 18 
19         //遍歷save中存儲的數據,將數據轉換成XML格式
20         for(int i = 0; i < save.livingTargetPositions.Count; i++) 21  { 22             target = xmlDoc.CreateElement("target"); 23             targetPosition = xmlDoc.CreateElement("targetPosition"); 24             //設置InnerText值
25             targetPosition.InnerText = save.livingTargetPositions[i].ToString(); 26             monsterType = xmlDoc.CreateElement("monsterType"); 27             monsterType.InnerText = save.livingMonsterTypes[i].ToString(); 28 
29             //設置節點間的層級關係 root -- target -- (targetPosition, monsterType)
30  target.AppendChild(targetPosition); 31  target.AppendChild(monsterType); 32  root.AppendChild(target); 33  } 34 
35         //設置射擊數和分數節點並設置層級關係 xmlDoc -- root --(target-- (targetPosition, monsterType), shootNum, score)
36         XmlElement shootNum = xmlDoc.CreateElement("shootNum"); 37         shootNum.InnerText = save.shootNum.ToString(); 38  root.AppendChild(shootNum); 39 
40         XmlElement score = xmlDoc.CreateElement("score"); 41         score.InnerText = save.score.ToString(); 42  root.AppendChild(score); 43 
44  xmlDoc.AppendChild(root); 45  xmlDoc.Save(filePath); 46 
47         if(File.Exists(Application.dataPath + "/StreamingFile" + "/byXML.txt")) 48  { 49             UIManager._instance.ShowMessage("保存成功"); 50  } 51     }
SaveByXml
 1 private void LoadByXml()  2  {  3         string filePath = Application.dataPath + "/StreamingFile" + "/byXML.txt";  4         if(File.Exists(filePath))  5  {  6             Save save = new Save();  7             //加載XML文檔
 8             XmlDocument xmlDoc = new XmlDocument();  9  xmlDoc.Load(filePath); 10 
11             //經過節點名稱來獲取元素,結果爲XmlNodeList類型
12             XmlNodeList targets = xmlDoc.GetElementsByTagName("target"); 13             //遍歷全部的target節點,並得到子節點和子節點的InnerText
14             if(targets.Count != 0) 15  { 16                 foreach(XmlNode target in targets) 17  { 18                     XmlNode targetPosition = target.ChildNodes[0]; 19                     int targetPositionIndex = int.Parse(targetPosition.InnerText); 20                     //把獲得的值存儲到save中
21  save.livingTargetPositions.Add(targetPositionIndex); 22 
23                     XmlNode monsterType = target.ChildNodes[1]; 24                     int monsterTypeIndex = int.Parse(monsterType.InnerText); 25  save.livingMonsterTypes.Add(monsterTypeIndex); 26  } 27  } 28             
29             //獲得存儲的射擊數和分數
30             XmlNodeList shootNum = xmlDoc.GetElementsByTagName("shootNum"); 31             int shootNumCount = int.Parse(shootNum[0].InnerText); 32             save.shootNum = shootNumCount; 33 
34             XmlNodeList score = xmlDoc.GetElementsByTagName("score"); 35             int scoreCount = int.Parse(score[0].InnerText); 36             save.score = scoreCount; 37 
38  SetGame(save); 39             UIManager._instance.ShowMessage(""); 40 
41  } 42         else
43  { 44             UIManager._instance.ShowMessage("存檔文件不存在"); 45  } 46     }
LoadByXml

 

在Json進行數據轉換時報錯:JsonException: Max allowed object depth reached while trying to export from type System.Singleorm

是由於數據中有float類型xml

如下是Json支持的類型對象

轉載自:https://blog.csdn.net/lihuozhiling0101/article/details/43152813blog

相關文章
相關標籤/搜索