Hello, I am having trouble with my inventory/item usage system (C#)
I have a base class Item, and a child class Weapon(more child classes in the future) that inherits from Item, and an Inventory array of type Item that can hold those items.
Now if i create a new Weapon() (because it inherits from Item it can still be put to Item straight away even if its Weapon)and put it in the Inventory array everything is fine, i can access the variables in Item class, but not Weapon, and now I don’t know what to do, because if I want to find out what Attack or something, that weapon has, I cant.
Because I put it into an Item array, I cannot see its class Weapon variables unless I assign it to a Weapon variable while casting it as Weapon (since I’m assigning an Item class from the array to that new Weapon variable)
And I’m sure there has to be some better way, or I’m totally going the wrong way here, or I’m missing something here, some guidance and help and/or examples would be much appreciated.
What I want to achieve is: Have an Item class array that I can put all its child classes (weapon, armor, ammo, etc.) but be able to see and use the different child variables.
I hope these code examples might make it any clearer.
public class Item { // Base Class
private string _name; // Variable
// Default/custom constructors and setters/getters somewhere here
}
public class Weapon : Item{ // Child class inherits from Item
private int _attack; // Variable
// Default/custom constructors and setters/getters somewhere here
}
private static Item[] _Inventory1 = new Item[50]; // The Item class inventory array
Inventory1[0] = new Weapon(); // puts a weapon class in the first slot of the array
Inventory[0].Name = "lalalal"; <--- Works fine
Inventory [0].Attack = 50; <--- does not because Attack is Weapon class variable and not Item...