1. 程式人生 > >Unity資料儲存(二進位制,xml,json)

Unity資料儲存(二進位制,xml,json)

//二進位制方法:存檔和讀檔
    private void SaveByBin()
    {
        //序列化過程(將Save物件轉換為位元組流)
        //建立Save物件並儲存當前遊戲狀態
        Save save = CreateSaveGO();
        //建立一個二進位制格式化程式
        BinaryFormatter bf = new BinaryFormatter();
        //建立一個檔案流
        FileStream fileStream = File.Create(Application.dataPath + "/StreamingFile" + "/byBin.txt");
        //用二進位制格式化程式的序列化方法來序列化Save物件,引數:建立的檔案流和需要序列化的物件
        bf.Serialize(fileStream, save);
        //關閉流
        fileStream.Close();

        //如果檔案存在,則顯示儲存成功
        if (File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            UIManager._instance.ShowMessage("儲存成功");
        }
    }

    private void LoadByBin()
    {
        if(File.Exists(Application.dataPath + "/StreamingFile" + "/byBin.txt"))
        {
            //反序列化過程
            //建立一個二進位制格式化程式
            BinaryFormatter bf = new BinaryFormatter();
            //開啟一個檔案流
            FileStream fileStream = File.Open(Application.dataPath + "/StreamingFile" + "/byBin.txt", FileMode.Open);
            //呼叫格式化程式的反序列化方法,將檔案流轉換為一個Save物件
            Save save = (Save)bf.Deserialize(fileStream);
            //關閉檔案流
            fileStream.Close();

            SetGame(save);
            UIManager._instance.ShowMessage("");

        }
        else
        {
            UIManager._instance.ShowMessage("存檔檔案不存在");
        }

        
    }

    //XML:存檔和讀檔
    private void SaveByXml()
    {
        Save save = CreateSaveGO();
        //建立XML檔案的儲存路徑
        string filePath = Application.dataPath + "/StreamingFile" + "/byXML.txt";
        //建立XML文件
        XmlDocument xmlDoc = new XmlDocument();
        //建立根節點,即最上層節點
        XmlElement root = xmlDoc.CreateElement("save");
        //設定根節點中的值
        root.SetAttribute("name", "saveFile1");

        //建立XmlElement
        XmlElement target;
        XmlElement targetPosition;
        XmlElement monsterType;

        //遍歷save中儲存的資料,將資料轉換成XML格式
        for(int i = 0; i < save.livingTargetPositions.Count; i++)
        {
            target = xmlDoc.CreateElement("target");
            targetPosition = xmlDoc.CreateElement("targetPosition");
            //設定InnerText值
            targetPosition.InnerText = save.livingTargetPositions[i].ToString();
            monsterType = xmlDoc.CreateElement("monsterType");
            monsterType.InnerText = save.livingMonsterTypes[i].ToString();

            //設定節點間的層級關係 root -- target -- (targetPosition, monsterType)
            target.AppendChild(targetPosition);
            target.AppendChild(monsterType);
            root.AppendChild(target);
        }

        //設定射擊數和分數節點並設定層級關係  xmlDoc -- root --(target-- (targetPosition, monsterType), shootNum, score)
        XmlElement shootNum = xmlDoc.CreateElement("shootNum");
        shootNum.InnerText = save.shootNum.ToString();
        root.AppendChild(shootNum);

        XmlElement score = xmlDoc.CreateElement("score");
        score.InnerText = save.score.ToString();
        root.AppendChild(score);

        xmlDoc.AppendChild(root);
        xmlDoc.Save(filePath);

        if(File.Exists(Application.dataPath + "/StreamingFile" + "/byXML.txt"))
        {
            UIManager._instance.ShowMessage("儲存成功");
        }
    }


    private void LoadByXml()
    {
        string filePath = Application.dataPath + "/StreamingFile" + "/byXML.txt";
        if(File.Exists(filePath))
        {
            Save save = new Save();
            //載入XML文件
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filePath);

            //通過節點名稱來獲取元素,結果為XmlNodeList型別
            XmlNodeList targets = xmlDoc.GetElementsByTagName("target");
            //遍歷所有的target節點,並獲得子節點和子節點的InnerText
            if(targets.Count != 0)
            {
                foreach(XmlNode target in targets)
                {
                    XmlNode targetPosition = target.ChildNodes[0];
                    int targetPositionIndex = int.Parse(targetPosition.InnerText);
                    //把得到的值儲存到save中
                    save.livingTargetPositions.Add(targetPositionIndex);

                    XmlNode monsterType = target.ChildNodes[1];
                    int monsterTypeIndex = int.Parse(monsterType.InnerText);
                    save.livingMonsterTypes.Add(monsterTypeIndex);
                }
            }
            
            //得到儲存的射擊數和分數
            XmlNodeList shootNum = xmlDoc.GetElementsByTagName("shootNum");
            int shootNumCount = int.Parse(shootNum[0].InnerText);
            save.shootNum = shootNumCount;

            XmlNodeList score = xmlDoc.GetElementsByTagName("score");
            int scoreCount = int.Parse(score[0].InnerText);
            save.score = scoreCount;

            SetGame(save);
            UIManager._instance.ShowMessage("");

        }
        else
        {
            UIManager._instance.ShowMessage("存檔檔案不存在");
        }
    }

    //JSON:存檔和讀檔
    private void SaveByJson()
    {
        Save save = CreateSaveGO();
        string filePath = Application.dataPath + "/StreamingFile" + "/byJson.json";
        //利用JsonMapper將save物件轉換為Json格式的字串
        string saveJsonStr = JsonMapper.ToJson(save);
        //將這個字串寫入到檔案中
        //建立一個StreamWriter,並將字串寫入檔案中
        StreamWriter sw = new StreamWriter(filePath);
        sw.Write(saveJsonStr);
        //關閉StreamWriter
        sw.Close();

        UIManager._instance.ShowMessage("儲存成功");
    }

    private void LoadByJson()
    { 
        string filePath = Application.dataPath + "/StreamingFile" + "/byJson.json";
        if(File.Exists(filePath))
        {
            //建立一個StreamReader,用來讀取流
            StreamReader sr = new StreamReader(filePath);
            //將讀取到的流賦值給jsonStr
            string jsonStr = sr.ReadToEnd();
            //關閉
            sr.Close();

            //將字串jsonStr轉換為Save物件
            Save save = JsonMapper.ToObject<Save>(jsonStr);
            SetGame(save);
            UIManager._instance.ShowMessage("");
        }
        else
        {
            UIManager._instance.ShowMessage("存檔檔案不存在");
        }
    }