有人请帮忙!这对我来说真的很困惑。我在互联网上找不到能够解释得这么好的人。所以这就是我需要的: 我需要有人解释如何在Unity中创建XML文件。人们告诉我要看一个流作家。我已经搜索了这个,但没有人给出如何编写它的教程。我也不知道.NET是什么,所以请不要给我这个答案。我也浏览了微软页面的XML文件,但我找不到正确的答案。这就是我正在寻找的所有内容:
我希望能够写出这样的内容:
<Player>
<Level>5<\Level>
<Health>500<\Health>
<\Player>
如何创建这样的文件并将其导入Unity?如何让Unity读取此文件并从此类提取信息?对于整个.NET和XML,我总共需要n00b。
答案 0 :(得分:14)
假设您有一个 Player 类,如下所示:
[XmlRoot]
public class Player
{
[XmlElement]
public int Level { get; set; }
[XmlElement]
public int Health { get; set; }
}
这是一个完整的往返途径,可以帮助您入门:
XmlSerializer xmls = new XmlSerializer(typeof(Player));
StringWriter sw = new StringWriter();
xmls.Serialize(sw, new Player { Level = 5, Health = 500 });
string xml = sw.ToString();
Player player = xmls.Deserialize(new StringReader(xml)) as Player;
xml 是:
<?xml version="1.0" encoding="utf-16"?>
<Player xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Level>5</Level>
<Health>500</Health>
</Player>
你猜播放器与我们序列化的原始对象完全相同。
如果要从文件序列化/反序列化,可以执行以下操作:
using (var stream = File.OpenWrite("my_player.xml"))
{
xmls.Serialize(stream, new Player { Level = 5, Health = 500 });
}
Player player = null;
using (var stream = File.OpenRead("my_player.xml"))
{
player = xmls.Deserialize(stream) as Player;
}
修改强>
如果您想要显示您所显示的XML:
XmlSerializer xmls = new XmlSerializer(typeof(Player));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };
using (var stream = File.OpenWrite("my_player.xml"))
{
using (var xmlWriter = XmlWriter.Create(stream, settings))
{
xmls.Serialize(xmlWriter, new Player { Level = 5, Health = 500 }, ns);
}
}
Player player = null;
using (var stream = File.OpenRead("my_player.xml"))
{
player = xmls.Deserialize(stream) as Player;
}