- Home /
The question is answered, right answer was accepted
How do I make my item only open if there is room in my Inventory?
I am trying to only opening an item if there is room in my inventory. Here is a segment of my code.
if(e.isMouse && e.type == EventType.mouseDown && e.button == 1)
{
if(item.itemType == Item.ItemType.Consumable)
{
UseConsumable(slots[i],i);
}
}
//////////////////////////////////////Segment//////////////////////////////////
void UseConsumable(Item item, int slot)
{
switch(item.itemID)
{
case 22:
{
inventory[slot] = new Item();
AddItem(20);
AddItem(23);
AddItem(24);
AddItem(25);
break;
}
}
}
void RemoveItem(int id)
{
for(int i = 0; i < inventory.Count; i++)
{
if(inventory[i].itemID == id)
{
inventory[i] = new Item();
break;
}
}
}
void AddItem(int id)
{
for(int i = 0; i< inventory.Count; i++)
{
if(inventory[i].itemName == null)
{
for(int j = 0; j < database.items.Count; j++)
{
if(database.items[j].itemID == id)
{
inventory[i] = database.items[j];
}
}
break;
}
}
}
bool InventoryContains(int id)
{
for (int i = 0; i < inventory.Count; i++)
if (inventory[i].itemID == id) return true;
return false;
}
I included the parts after use consumable so you can have a better idea. I tried doing an if statement but I can't even think what I would put for it to get this to work. The overall goal is to only open the my item if there is four slots of inventory available. Any Ideas?
I can do if(InventoryContains(-1)){
to get it to only open if there is one slot of nothing but I can't figure out how to make it multiple slots.
Answer by ThePokedog1 · Aug 19, 2015 at 10:20 PM
Got it to work! Did this instead inside the GetInventorySpace()
if(inventory[i].itemID == -1)
Answer by Maui-M · Aug 19, 2015 at 09:40 PM
You could add a new function to find the count of empty slots:
int GetInventorySpace()
{
int count = 0;
for (int i = 0; i < inventory.Count; i++)
if (inventory[i].itemID == -1) count += 1;
return count;
}
Then just check if GetInventorySpace() >= 4. The other option would be to have a variable change when you add or remove items from your inventory.
Answer by NeverHopeless · Aug 19, 2015 at 10:03 PM
You may try this:
if(item.itemType == Item.ItemType.Consumable && i < slot.Length - 4)
{
UseConsumable(slots[i],i);
}
Here i < slot.Length - 4
will prevent to go in this condition there are less than 4 slot available.
Follow this Question
Related Questions
unity3d simple inventory 1 Answer
How can I delete an item from this inventory system? 1 Answer
[C#] Grouping variables 1 Answer
adding inventory items is half-working 0 Answers
Object Reference Not Set To An Instance of An Object Error 1 Answer