推荐使用System.Xml.Linq(LINQ to XML)读取XML配置文件,将config.xml放入Assets/Resources/Configs/并用Resources.Load("Configs/config")获取TextAsset,再通过XDocument.Parse(textAsset.text)解析;也可用XmlSerializer反序列化为强类型对象,需注意UTF-8无BOM编码、平台兼容性及缓存优化。

Unity中读取XML配置文件,推荐用C#原生的System.Xml或更现代的System.Xml.Linq(即LINQ to XML)。前者兼容性好,后者语法简洁、易读易写,适合大多数项目。
把XML文件放进Resources文件夹(最简单方式)
Unity不支持直接用File.ReadAllText读取任意路径的XML(尤其在WebGL或移动端),所以建议把配置文件放在Assets/Resources/下,用Resources.Load加载:
- 将
config.xml放入Assets/Resources/Configs/(路径可自定义) - 确保文件扩展名是
.xml,且Unity未将其识别为文本资源以外的类型(可在Inspector里确认Text Asset类型) - 代码中用
Resources.Load获取——注意不用写("Configs/config") .xml后缀
用XDocument解析XML(推荐LINQ to XML)
XDocument比XmlDocument更轻量、API更直观。加载完TextAsset后,用其text属性创建XDocument:
XDocument doc = XDocument.Parse(textAsset.text); var root = doc.Root; // 例如读取double volume = (double)root.Attribute("volume"); bool fullscreen = (bool)root.Attribute("fullscreen"); // 读取子节点: var level = root.Element("Level"); string levelName = level?.Attribute("name")?.Value; string difficulty = level?.Attribute("difficulty")?.Value;
用XmlSerializer反序列化成对象(适合结构固定场景)
如果XML格式规范、和C#类一一对应,可用XmlSerializer自动映射。先定义带[XmlRoot]、[XmlElement]等特性的类:
[XmlRoot("GameSettings")]
public class GameConfig
{
[XmlAttribute] public float volume;
[XmlAttribute] public bool fullscreen;
[XmlElement("Level")] public List levels;
}
public class LevelData
{
[XmlAttribute] public string name;
[XmlAttribute] public string difficulty;
}
// 使用:
var serializer = new XmlSerializer(typeof(GameConfig));
using var reader = new StringReader(textAsset.text);
GameConfig config = (GameConfig)serializer.Deserialize(reader);
注意:XmlSerializer要求类为public,字段/属性有public get/set,且不能有无参构造函数缺失等问题。
注意事项和常见坑
Unity Editor里测试正常,但打包后可能出错,主要因路径或编码问题:










