xml管理脚本

使用这个管理脚本若要序列化字典数据类型需要自己写一个继承IXmlSerializer接口的Dictionnary

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;

public class XmlDataMgr 
{
    private static XmlDataMgr instance = new XmlDataMgr();
    public static XmlDataMgr Instance => instance;
    private XmlDataMgr() { }

    public void SaveData(object data,string fileName)
    {
        //得到路径
        string path = Application.persistentDataPath + "/" + fileName + ".xml";
        //存储文件
        using (StreamWriter writer = new StreamWriter(path))
        {
            //序列化
            XmlSerializer s = new XmlSerializer(data.GetType());
            s.Serialize(writer, data);
        }
    }

    public object LoadData(Type type,string fileName)
    {
        //判断文件是否存在
        string path = Application.persistentDataPath + "/" + fileName + ".xml";
        //存在就读取
        if(!File.Exists(path))
        {
            path = Application.streamingAssetsPath + "/" + fileName + ".xml";
            if(!File.Exists(path))
            {
                //如果两个路径都没有文件 那么new一个type类型对象返回给外部 都是默认值
                return Activator.CreateInstance(type);
            }
        }
        using (StreamReader reader = new StreamReader(path))
        {
            //反序列化
            XmlSerializer s = new XmlSerializer(type);
            return s.Deserialize(reader);
        }
    }
}