I am designing a very simple inventory system for a game. I have run into an obstacle where I have the inventory (an array of a specific type) that would need to accept multiple types of objects. My code:
IWeapon[] inventory = new IWeapon[5];
public void initialiseInventory(IWeapon weapon, IArmour armour)
{
inventory[0] = weapon; // Index 0 always contains the equipped weapon
inventory[1] = armour; // Index 1 always contains the equipped armour
}
I would get an error stating that the array can't convert the armour object to a weapon object (which is the array type). I then thought I might make a superclass (well, interface to be precise) that IWeapon and IArmour would inherit from. But then I run into another error...
IItem[] inventory = new IItem[5];
public void initialiseInventory(IWeapon weapon, IArmour armour)
{
inventory[0] = weapon; // Index 0 always contains the equipped weapon
inventory[1] = armour; // Index 1 always contains the equipped armour
Console.WriteLine("The weapon name is: " + inventory[0].Name) // Problem!
}
Since the array type is IItem, it would only contain properties and methods from IItem, and not from IWeapon or IArmour. Thus the problem came in that I could not access the name of the weapon located in the subclass (subinterface) IWeapon. Is there a way I could redirect it somehow to look for properties in a subinterface (IWeapon or IArmour) rather than the superinterface (IItem)? Am I even on the right path?
Since the first item will always be a weapon, and the second will always be armor, you shouldn't use an array (or any data structure) at all. Just have two separate fields, one that holds a weapon and another an armor instance.
private IWeapon weapon;
private IArmour armor;
public void initialiseInventory(IWeapon weapon, IArmour armour)
{
this.weapon = weapon;
this.armor = armor;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With