コード例 #1
0
    private void SaveXmlData()
    {
        // 创建 save 对象和 xml 文档对象
        Save        save        = CreateSaveObject();
        XmlDocument xmlDocument = new XmlDocument();

        #region Xml 存档数据生成
        XmlElement root = xmlDocument.CreateElement("Save");

        // 金币得分
        XmlElement CoinNum = xmlDocument.CreateElement("CoinNum");
        CoinNum.InnerText = save.coin.ToString();
        root.AppendChild(CoinNum);

        // 玩家位置
        XmlElement PlayerPosX = xmlDocument.CreateElement("PlayerPosX");
        XmlElement PlayerPosY = xmlDocument.CreateElement("PlayerPosY");
        XmlElement PlayerPosZ = xmlDocument.CreateElement("PlayerPosZ");

        PlayerPosX.InnerText = save.playerPosX.ToString();
        PlayerPosY.InnerText = save.playerPosY.ToString();
        PlayerPosZ.InnerText = save.playerPosZ.ToString();

        root.AppendChild(PlayerPosX);
        root.AppendChild(PlayerPosY);
        root.AppendChild(PlayerPosZ);

        // 各个金币的状态
        XmlElement Coin, isDead, CoinPosX, CoinPosY, CoinPosZ;

        for (int i = 0; i < coins.Length; i++)
        {
            Coin     = xmlDocument.CreateElement("Coin");
            isDead   = xmlDocument.CreateElement("isDead");
            CoinPosX = xmlDocument.CreateElement("CoinPosX");
            CoinPosY = xmlDocument.CreateElement("CoinPosY");
            CoinPosZ = xmlDocument.CreateElement("CoinPosZ");

            isDead.InnerText   = save.coins[i].isDead.ToString();
            CoinPosX.InnerText = save.coins[i].x.ToString();
            CoinPosY.InnerText = save.coins[i].y.ToString();
            CoinPosZ.InnerText = save.coins[i].z.ToString();

            Coin.AppendChild(isDead);
            Coin.AppendChild(CoinPosX);
            Coin.AppendChild(CoinPosY);
            Coin.AppendChild(CoinPosZ);

            root.AppendChild(Coin);
        }

        // 添加 root 节点到 xml 文档中
        xmlDocument.AppendChild(root);

        #endregion

        // 存储 xml 文档到 save.xml 文件中
        xmlDocument.Save(Application.dataPath + "/SaveData/save.xml");

        if (File.Exists(Application.dataPath + "/SaveData/save.xml"))
        {
            Debug.Log("存档成功");
        }
    }