I'd like to apologize in advance for the amount of text that follows. I am learning C# and really got stuck on a task thats probably trivial to advanced users, but searching the internet has brought me to no solution:
In my RPG I have an array that's suposed to hold multiple items (Health Potion, Mana Potion, ...). I want the player to choose which one to use and then call the method thats coresponding to the item.
I define the globaly accesible array thats supossed to hold all items:
static class Globals
{
public static object[] playerItems = new object[1];
}
Then I define the class "Item":
public class Item
{
public string itemName;
public string itemType;
public int itemValue;
}
Then I define the sub-class HealingPotion, which inherits some but not all variables from the item class. I also define the method to use the item:
public class HealingPotion : Item
{
public int healingValue;
public HealingPotion (string name, string type, int value, int healingV)
{
itemName = name;
itemType = type;
itemValue = value;
healingValue = healingV;
void usePotion()
{
Globals.playerCurrentHp = Globals.playerCurrentHp + healingV;
Then I create a first item:
public static void Main()
{
HealingPotion SmallPotion = new HealingPotion("Kleiner Heiltrank", "small potion", 10, 15);
And then, when the player wants to use an item, I have all items listed to him (inside a method):
int numberOfItems = Globals.playerItems.Length;
for (int i=0 ; i<numberOfItems; i++)
{
Console.WriteLine(" ("+i+") "+((Item)Globals.playerItems[i]).itemName);
}
Now this is where I get stuck: How can I call the corresponding method of the object(item) that the player choses to use? In my example, if the player chooses the healing potion out of many different items, how can I automatically call the UsePotion Method that I defined earlier? I guess I can have all methods in all item-subclasses be called the same (e.g.UseItem() ), but that limits me to a single method per item and forces me to call all methods the same name.
Is there a smarter way to call the method that coresponds to the item the player choses to use? Can I "get" the available methods from knowing the object?