Hello其他程序员。我有一个关于在Unity3d中制作游戏的问题,但它更多的是关于C#。 我有一个名为Item的类(它只包含字符串itemname和int值)。我还有一个叫做制作配方的类,带有一个名为output的项目,这里有一件我不确定的事情,我应该使用inputitems变量的字典或通用列表。此外,在创建库存类时,我是否使用库存中的项目的字典或通用列表。
虽然这是我真正需要帮助的部分(我之前尝试过但未成功),我怎么做到这一点,当我工艺时,它检查清单中的我的项目,如果我有所需的所有项目在库存中(因此检查我的库存中是否包含所有输入项),它将删除它们,并将输出项添加到库存中。我也使用C#。 谢谢:))
编辑这是一个例子::
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Inventory : MonoBehaviour {
//Should this be a dictionary.
public List<Item> InventoryList = new List<Item>();
}
public class Item{
public string ItemName;
public int ItemValue;
}
public class CraftingItem{
//Should I make this a dictionary or leave it?
public List<Item> InputItems = new List<Item>();
public Item Output;
}
答案 0 :(得分:2)
我会用以下方式做到这一点:
class Program
{
public class Inventory : List<Item>
{
public int Weight { get; set; }
// some other properties
}
public class Item : IEquatable<Item>
{
public string Name { get; set; }
public int Value { get; set; }
public bool Equals(Item other)
{
return this.Name == other.Name;
}
}
public class ItemsComparer : IEqualityComparer<Item>
{
public bool Equals(Item x, Item y)
{
if (x.Name.Equals(y.Name)) return true;
return false;
}
public int GetHashCode(Item obj)
{
return 0;
}
}
public class CraftingRecipe
{
private List<Item> _recipe;
private Item _outputItem;
public CraftingRecipe(List<Item> recipe, Item outputItem)
{
_recipe = recipe;
_outputItem = outputItem;
}
public Item CraftItem(Inventory inventory)
{
if (_recipe == null)
{
//throw some ex
}
var commonItems = _recipe.Intersect(inventory, new ItemsComparer()).ToList();
if (commonItems.Count == _recipe.Count)
{
inventory.RemoveAll(x => commonItems.Any(y => y.Name == x.Name));
return _outputItem;
}
return null;
}
}
static void Main(string[] args)
{
List<Item> recipeItems = new List<Item>()
{
new Item { Name = "Sword" } ,
new Item { Name = "Magic Stone" }
};
Item outputItem = new Item() { Name ="Super magic sword" };
Inventory inventory = new Inventory()
{
new Item { Name = "Sword" } ,
new Item { Name = "Ring" },
new Item { Name = "Magic Stone" }
};
CraftingRecipe craftingRecipe =
new CraftingRecipe(recipeItems, outputItem);
var newlyCraftedItem = craftingRecipe.CraftItem(inventory);
if (newlyCraftedItem != null)
{
Console.WriteLine(newlyCraftedItem.Name);
}
else
{
Console.WriteLine("Your item has not been crafted");
}
Console.Read();
}