using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//引用命名空间
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using UnityEngine.SocialPlatforms.Impl;
/// <summary>
/// 创建Date储存数据
/// </summary>
public class Date
{
public int Score;//分数
}
/// <summary>
/// Xml储存
/// </summary>
public class XmlDateSave : MonoBehaviour
{
public static XmlDateSave Instance;
private void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
}
else
{
Instance = this;
}
}
//创建Data对象,并向其中添加游戏需要保存的数据
private Date GetGameDate()
{
Date date = new Date();
date.Score = Btnnnnn.Instance.Score;
return date;
}
//向游戏中加载Date中保存的数据的方法
private void SetGameDate(Date date)
{
Btnnnnn.Instance.Score = date.Score;
}
//对数据进行保存
public void SaveByXml()
{
Date date = GetGameDate();
string datePath = Application.streamingAssetsPath + "/byXml.txt";//文件路径+文件名
XmlDocument xmlDoc = new XmlDocument();//创建XML文档
XmlElement root = xmlDoc.CreateElement("saveByXml1");//创建根节点,并设置根节点的名字
root.SetAttribute("name", "分数");//设置根节点的值
//创建其他节点,并设置其他节点的值
XmlElement xmlEle = xmlDoc.CreateElement("总分数");
xmlEle.InnerText = date.Score.ToString();
//将子节点加入根节点,将根节点加入XML文档中
root.AppendChild(xmlEle);
xmlDoc.AppendChild(root);
//最后保存文件
xmlDoc.Save(datePath);
}
//对数据进行读取
public void LoadByXml()
{
string datePath = Application.streamingAssetsPath + "/byXml.txt";
if (File.Exists(datePath))
{
Date date = new Date();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(datePath); //加载这个路径下的xml文档
XmlNodeList xmlNod = xmlDoc.GetElementsByTagName("总分数");//通过名字得到XML文件下对应的值
date.Score = int.Parse(xmlNod[0].InnerText);
SetGameDate(date);
}
else
{
Debug.Log("没有找到:" + datePath);
}
}
private void Update()
{
Test();
}
/// <summary>
/// 测试
/// </summary>
void Test()
{
if (Input.GetKeyDown(KeyCode.S))
{
SaveByXml();
}if (Input.GetKeyDown(KeyCode.L))
{
LoadByXml();
}
}
}
Xml对数据的存储与读写
最新推荐文章于 2024-07-12 16:26:51 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)