在unity的streamingAssets文件夹下创建xml
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Xml;
public class SaveIPAndPort : MonoBehaviour
{
private string ipAddress = "127.0.0.1";
private int port = 8888;
string filePath = Application.streamingAssetsPath + "/config.xml";
void Start()
{
//判断文件是否存在
if (!File.Exists(filePath))
{
SaveToXML();
}
}
void SaveToXML()
{
XmlDocument xmlDoc = new XmlDocument();
XmlElement rootNode = xmlDoc.CreateElement("Config");
xmlDoc.AppendChild(rootNode);
XmlElement ipNode = xmlDoc.CreateElement("IP");
ipNode.InnerText=ipAddress;
rootNode.AppendChild(ipNode);
XmlElement portNode = xmlDoc.CreateElement("Port");
portNode.InnerText=port.ToString();
rootNode.AppendChild(portNode);
xmlDoc.Save(filePath);
}
}
读取streamingAssets文件夹下的config.xml文件
using System.Xml;
using UnityEngine;
public class Duq: MonoBehaviour
{
private string ipAddress;
private int port;
void Start()
{
ReadFromXML();
Debug.Log("IP地址:"+ipAddress);
Debug.Log("端口号:"+port);
}
void Update()
{
}
void ReadFromXML()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Application.streamingAssetsPath + "/config.xml");
XmlNodeList ipNodes = xmlDoc.GetElementsByTagName("IP");
XmlNodeList portNodes = xmlDoc.GetElementsByTagName("Port");
if (ipNodes.Count > 0 && portNodes.Count > 0)
{
ipAddress = ipNodes[0].InnerText;
port = int.Parse(portNodes[0].InnerText);
Debug.Log("IP Address: " + ipAddress + ", Port: " + port);
}
else
{
Debug.LogError("Failed to read IP address and port from XML file.");
}
}
}