Unity - writing and reading XML, creating XML when publishing acts as network settings xml

Create xml when publishing

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

public class XmlCreator {
    //必须放在editor文件夹下
    [UnityEditor.Callbacks.PostProcessBuild]
    public static void OnPostprocessBuild(UnityEditor.BuildTarget target, string pathToBuiltProject)
    {
        // 创建XML文件
        UDPRecvice.Internet settings = new UDPRecvice.Internet ();
        settings.IP = "你的IP";
        settings.Port = 端口号;
        string xmlFilePath = Path.Combine(Path.GetDirectoryName(pathToBuiltProject), "网络设置.xml");
        using (StreamWriter streamWriter = new StreamWriter(xmlFilePath))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(UDPRecvice.Internet ));
            serializer.Serialize(streamWriter, settings);
        }
    }

}

Script to read and write xml

 //克隆项目需要先右键写入一份网络设置.xml,这时候场景中会多出来个物体,之后可以删掉.或者直接start里面运行,场景中不会多出来一个物体(运行后销毁了)
        [ContextMenu("写入网络设置XML")]
        public void WriteXML()
        {
            //反序列读取实例,运行后就有XML了然后反序列化读取          
            Internet  setting  = new Internet();
            Internet .IP = "你的IP";
            Internet .Port = 端口号;
            //最关键的一步:序列化生成XML.
            string path = Application.dataPath + "/网络设置.xml";
            SerializerXml.Instance.SaveToXml(path, 网络设置);
        }

        [ContextMenu("读取网络设置XML")]
        public void ReadXML()
        {
            string path = Path.Combine(Application.dataPath, "../网络设置.xml");
            //编辑器模式时读取项目Assets文件夹内的网络设置.xml
            if (Application.platform == RuntimePlatform.WindowsEditor)
            {
                path = Application.dataPath + "/网络设置.xml";
            }
            //发布模式时读取位于发布文件夹内(Assets的上一级)的网轮设置.xml
            else if(Application.platform == RuntimePlatform.WindowsPlayer)
            {
                path = Path.Combine(Application.dataPath, "../网络设置.xml");
            }
            Internet setting = SerializerXml.Instance.LoadFormXml(path, typeof(Internet)) as Internet;
            this.ip = Internet.IP;
            this.port = Internet.Port;
        }

 public class Internet {
            public string IP = "你的IP";

            public int Port = 你的端口号;
        }

Create xml and read xml in the editor

using UnityEngine;
using System.Xml.Serialization;//引入命名空间,负责把对象序列化到xml,并从xml中反序列化
using System;
using System.IO;
public class SerializerXml : MonoBehaviour {
    static SerializerXml instance;
    /// <summary>
    /// Start this instance.单例
    /// </summary>
    public static SerializerXml Instance
    {
        get
        {
            if (instance == null)
            {
                GameObject singleton = new GameObject();
                singleton.name = "SerializerXmlManager";
                instance = singleton.AddComponent<SerializerXml>();
            }
            return instance;
        }
    }

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }

    /// <summary>
    /// Saves to xml.保存xml
    /// </summary>
    /// <param name="filePath">File path.文件的路径</param>
    /// <param name="sourceObj">Source object.源对象</param>
    /// <param name="Type">Type.类型 </param>
    /// <param name="xmlRootName">Xml root name.根节点的名字</param>
    public void SaveToXml(string filePath, object sourceObj, Type type = null, string xmlRootName = null)
    {
        if (!string.IsNullOrEmpty(filePath) && sourceObj != null)
        {
            type = type != null ? type : sourceObj.GetType();//三元表达式
                                                             //三元表达式等同于:
                                                             //          if (type != null) {
                                                             //              type = type;
                                                             //          } else {
                                                             //              type = sourceObj.GetType ();
                                                             //          }
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                XmlSerializer xmlSerializer = string.IsNullOrEmpty(xmlRootName) ? new XmlSerializer(type) : new XmlSerializer(type, new XmlRootAttribute(xmlRootName));
                xmlSerializer.Serialize(writer, sourceObj);
                Debug.Log("保存成功!");
            }
        }
    }

    /// <summary>
    /// Loads the form xml.加载xml
    /// </summary>
    /// <returns>The form xml. </returns>
    /// <param name="filePath">File path.xml路径 </param>
    /// <param name="type">Type. 反序列化类型</param>
    public object LoadFormXml(string filePath, Type type)
    {
        object result = null;
        if (File.Exists(filePath))
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(type);
                result = xmlSerializer.Deserialize(reader);
            }
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/weixin_42301988/article/details/130499219