unity封装一个方法 用来给字典中得背包数据进行类型分类
时间: 2024-09-07 19:03:02 浏览: 20
在Unity中封装一个方法来对背包数据进行分类,通常需要先定义背包中物品的数据结构,然后根据物品的类型来进行分类。下面是一个简单的示例方法:
首先,假设我们有一个物品的基类和几个派生类,代表不同类型的物品:
```csharp
public abstract class Item
{
public string Name { get; set; }
public int Quantity { get; set; }
// 其他通用属性
}
public class Weapon : Item
{
public int AttackPower { get; set; }
// 武器特有的属性
}
public class Armor : Item
{
public int DefensePower { get; set; }
// 护甲特有的属性
}
public class HealingPotion : Item
{
public int HealPoint { get; set; }
// 药水特有的属性
}
```
然后,我们可以创建一个背包类,它包含一个字典来存储不同类型的物品:
```csharp
public class Inventory
{
public Dictionary<Type, List<Item>> ItemsByType { get; private set; }
public Inventory()
{
ItemsByType = new Dictionary<Type, List<Item>>();
}
// 添加物品到背包的方法(示例,省略具体实现)
public void AddItem(Item item)
{
// 添加逻辑
}
// 封装一个分类的方法
public void ClassifyItems()
{
ItemsByType.Clear(); // 清空旧的分类结果
// 遍历背包中的所有物品,并按类型分类存储到字典中
foreach (var item in this.Items)
{
Type itemType = item.GetType();
if (!ItemsByType.ContainsKey(itemType))
{
ItemsByType[itemType] = new List<Item>();
}
ItemsByType[itemType].Add(item);
}
}
}
```
在上面的`Inventory`类中,`ClassifyItems`方法将会根据每个物品的实际类型,将它们分类存储到`ItemsByType`字典中。字典的键是`Type`对象,值是相同类型的物品列表。每当有新物品添加到背包中时,只需要调用`ClassifyItems`方法,即可更新背包中的物品分类。
使用示例:
```csharp
Inventory inventory = new Inventory();
inventory.AddItem(new Weapon());
inventory.AddItem(new Armor());
inventory.AddItem(new HealingPotion());
// 对物品进行分类
inventory.ClassifyItems();
// 现在可以根据类型访问分类后的物品了
List<Weapon> weapons = inventory.ItemsByType[typeof(Weapon)];
List<Armor> armors = inventory.ItemsByType[typeof(Armor)];
List<HealingPotion> potions = inventory.ItemsByType[typeof(HealingPotion)];
```