【发布时间】:2017-09-24 16:46:28
【问题描述】:
我正在尝试为我的游戏创建一个项目数据库。我希望它包含游戏中的所有物品(武器、消耗品、盔甲等)。但我希望它们都继承自一个名为 item 的父类。我见过的所有示例都使用单个项目类并且没有继承。
XML 中有没有一种方法可以使我的数据库在我反序列化它时,它们都将是正确的类型?武器将是武器类型,盔甲类型等。
我当前的 XML 和项目和容器:
<?xml version="1.0" encoding="UTF-8"?>
<ItemCollection>
<Items>
<DatabaseItem name="Sword">
<Damage>20</Damage>
</DatabaseItem>
<DatabaseItem name="Wand">
<Damage>10</Damage>
</DatabaseItem>
</Items>
</ItemCollection>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml.Serialization;
using System.IO;
[XmlRoot("itemCollection")]
public class ItemContainer
{
[XmlArray("Items")]
[XmlArrayItem("DatabaseItem")]
public List<DatabaseItem> items = new List<DatabaseItem>();
public static ItemContainer Load(string path)
{
TextAsset _xml = Resources.Load<TextAsset>(path);
XmlSerializer serializer = new XmlSerializer(typeof(ItemContainer));
StringReader reader = new StringReader(_xml.text);
ItemContainer items = serializer.Deserialize(reader) as ItemContainer;
reader.Close();
return items;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.Xml.Serialization;
public class DatabaseItem
{
[XmlAttribute("title")]
public string title;
[XmlAttribute("damage")]
public float damage;
}
【问题讨论】: