Currently working on a base RPG system, and I've run into an error with a method. The method is meant to add an item (Class within the code) and an optional amount to the players inventory (An Item[] array).
This is the code for the item class:
public class Item
{
public string Name;
public int quantity;
public int maxstack;
public int[] stats = new int[5];
public Item(string name, int Amount = 1, int MaxStack = 10, int ATK = 0,
int DEF = 0, int MAT = 0, int MDF = 0, int SPD = 0)
{
Name = name;
quantity = Amount;
maxstack = MaxStack;
stats[0] = ATK;
stats[1] = DEF;
stats[2] = MAT;
stats[3] = MDF;
stats[4] = SPD;
}
}
The key variables are "quantity" and "maxstack."
Now, the issue comes when adding an item to the players inventory, regarding these variables. The method, when adding an Item to the inventory, searches for both an empty slot within the inventory and any stacks of the same item using Array.IndexOf();
This is the code for the AddItem() method:
public void AddItem(Item item, int Amount = 1)
{
for (int i = Amount; i > 0; i--)
{
int ItemIndex = Array.IndexOf(inv, item); // Searches for a matching item
int EmptySlot = Array.IndexOf(inv, null); // Searches for an empty slot
ItemCheck:
if (ItemIndex != -1) // ItemIndex will equal -1 if no matching item was found
{
if (inv[ItemIndex].quantity >= inv[ItemIndex].maxstack) // Is the quantity/stack of the found item equal to its maximum stackable value?
{
ItemIndex = Array.IndexOf(inv, item, ItemIndex + 1); // If yes, search for another index.
goto ItemCheck;
} else {
inv[ItemIndex].quantity++; // If the stack hasn't reached its max, increase it by one.
}
}
else
{
inv[EmptySlot] = item; // If no matching item was found, use an empty slot to create a new stack.
inv[EmptySlot].quantity = 1;
}
}
}
Now, lets say I create an item called "stick" and it can only stack a maximum of 3. When running AddItem(stick, 3) and listing the quantity of each stack, the console returns
Stick x1
Stick x1
Can anyone help me? Why is my code turning the stack back into a quantity of 1?
EDIT:
Adding 1, 2 or 3 sticks returns the correct quantity, but only adding more sticks once a stack has reached its max throws the wrong result.
EDIT:
Adding 6 sticks returns 2 stacks with 3 items in each. Adding 7 sticks returns 3 stacks with 1 item in each.
Array.IndexOffound no item in the array that is equivalent in value to whateverItemobject you're passing to the function.goto...... you know the SO people want us to be nice to new people.... but sometimes I feel it's challenging :)gotoenables bad code flow; we know it, but not everybody does.