- Home /
Lists, and Crafting?
How do I like count how many different types of items, how many of them and return that value, use it quickly in my crafting script. So the recipe calls for 2 wood, 4 stone, it calls the CheckForItemsAndReturn() with (wood, 2), and (stone, 4), then adds the two lists, and then uses generic list.sort() and compares the two, if they are the same, then they would continue the craft method.; Thanks, Huskypanda
Code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerInventory : MonoBehaviour {
public int MaxInventory = 26;
public List<Item> InventoryItems = new List<Item>();
public void AddItem(Item _item){
}
public void Craft(CraftingItem Recipe){
Recipe.InputItem.Sort ();
List<Item> _items = new List<Item> ();
//Find out the number and use CheckForItemsAndReturn();!
if (Recipe.InputItem == _items) {
foreach(Item _it in _items){
InventoryItems.Remove(_it);
}
InventoryItems.Add(Recipe.OutputItem);
}
else{
Debug.Log("Invalid Items.");
}
}
//For Multiple
public List<Item> CheckForItemsAndReturn(Item checkfor, int count){
List<Item> il = new List<Item>();
foreach(Item it in InventoryItems){
if(it == checkfor){
if(il.Count <= count){
il.Add(it);
}
}
}
return il;
}
}
Answer by kei_kvaartz · Jan 15, 2014 at 06:33 PM
I would make CheckForItems a bool function that returns true if the items are found, and have the items (if found) spit out as an output parameter.
bool CheckForItems (List wantedItems, out List foundItems)
An example would help, also I can change to bool but then finding the items becomes more complecatd.
How would I compare all the items without getting the same entity of item twice. I know how to make it a bool but then it will compare all the items, and maybe give the same one twice. Also is there a way to make like for each item of wood in items list.
I would make a temporary list that is a copy of the inventory list.
List<item> temp = new List<item>();
foreach (Item i in inventory) {temp.Add(i);}
Then as you put items in the output list, remove them from the temp list. (Do not remove them from inventory.) This will prevent duplication.
Be careful with "foreach" in this kind of situation. You cannot modify a collection while "foreach"-ing through it. In this type of situation, I would reverse iterate through it, like this:
for (int j=temp.Count-1; j>=0; j--) {
if (Condition$$anonymous$$et(temp[j])) {
outList.Add(temp[j]);
temp.Remove(temp[j]);
}
}