Before I explain my problem, keep in mind that I went for an architecture like this because this is going to be used in an inventory system under Unity, so I had to separate the Item
which is a MonoBehavior which is just something in the world from its Data which are just values used for Inventory purposes... If that makes sense.
I have an architecture that goes like this:
public class ItemData
{
// some fields...
public string _name; //should be private with its properties but it doesn't matter in the current example
}
public class EquipmentData : ItemData
{
// some additional fields...
public float _weight;
}
public class Item
{
private ItemData _data;
//Properties
public virtual ItemData Data { get; set; }
}
public class Equipment : Item
{
//Properties
public override ItemData Data
{
get { return _data as EquipmentData; }
set { _data = value as EquipmentData; }
}
}
So, basically I have an item hierarchy that goes even deeper but 1 level is enough to explain myself. (It keeps going like Weapon : Equipment)...
The thing is, if I leave private ItemData _data;
in Item
class, and add a private EquipmentData _eData;
in Equipment
class, I will have the ItemData
fields twice since EquipmentData
inherits ItemData
and so on for the other derived classes... getting it a third time if I have a class that derives from Equipment
etc...
Something like:
public class Item
{
private ItemData _data;
}
public class Equipment : item
{
private EquipmentData _eData;
}
The fields of ItemData
such as _name
will appear twice in Equipment
and I don't want that...
So I am guessing there is something wrong with my architecture, and there might be a way around this method that looks kind of "dirty", but I couldn't find anything specific for this problem online and I have reached my limits.
What I have tried:
- I have tried using the keyword
new
inEquipment
thinking I could hide the initialprotected ItemData _data;
that is in myItem
class, and then haveprotected new EquipmentData _data;
inEquipment
but it obviously does not let me since to Shadow _data it needs to be the same type, doesn't seem to work with derived types. - Also, as shown in my code sample, I have tried overriding the property to return the proper type depending on the class it is called in, the casts always return
null
...
I still find it strange that I ended up trying to implement something like that, so I am open to new ideas to restructure things in a better way, or if someone has a solution I haven't thought of to keep things that way but make them work, it'd be very nice.
I hope I was detailed enough in my problem, if not I can clear things up if needed.