I'm truly sorry if the answer exist here under another name but I've been trying to figure this out for a week or so and haven't found anything similar.
So, I'm building an Item system for a game in unity. There is an Item class with these properties
public int ItemId;
public string ItemName;
For simplicity, let's say I want to have two derived classes, Weapon and Armor, with a BaseDamage property for Weapon and BaseArmor for Armor.
I also want to load the items in an ItemContainer class from XML and ideally, from the same XML file rather than one for the weapons, one for armors and one for, say, potions.
I've tried multiple ways but so far the only way I've been able to succeed is by adding the BaseDamage and BaseArmor to the Item base class... like this :
public class Item
{
[XmlAttribute("ID")] public int ItemID;
[XmlElement("Name")] public string ItemName;
[XmlElement("Damage")] public int ItemBaseDamage;
[XmlElement("Armor")] public int ItemBaseArmor;
}
and simply not adding the element to the XML file for some items :
<ItemCollection>
<Items>
<Item ID ="001">
<Name>Dagger</Name>
<Damage>10</Damage>
</Item>
<Item ID ="002">
<Name>Chain Mail</Name>
<Armor>5</Armor>
</Item>
</Items>
</ItemCollection>
It does work, but I feel like this isn't the correct way to do it. Another issue is that if I want to add a Scroll class with a certain function to cast the spell written on that scroll, I need to add the "SpellToCast" property to the base class AND add a CastSpell(Spell) function to it that could be called from any item, which is not what I want...
In short, I'd want to load multiple items from the XML but with each being of their intended derived class so that they get access to their respective functions and get their specific properties such as BaseDamage if it's a weapon.
I've tried to use an XmlElement called ItemClass of type class, but I get an error saying that XmlElement/XmlAttribute is not valid on this declaration type...
I also thought about using an abstract Item class instead but then how do I load the item ID to the abstract base class Item and then BaseDamage to the derived class, Weapon?
This is the code I use to (deserialize? I'm not sure that's the correct term) the XML file :
[XmlRoot("ItemCollection")]
public class ItemContainer
{
[XmlArray("Items")]
[XmlArrayItem("Item")]
public List<Item> items = new List<Item>();
public static ItemContainer Load(string itemPath)
{
TextAsset _xml = Resources.Load<TextAsset>(itemPath);
XmlSerializer serializer = new XmlSerializer(typeof(ItemContainer));
StringReader reader = new StringReader(_xml.text);
ItemContainer items = serializer.Deserialize(reader) as ItemContainer;
reader.Close();
return items;
}
}
So, any help is welcome,
Thanks