Unity笔记-背包管理器

背包管理器

创建InventoryManager脚本

```csharp
using xxx;//…
//背包格子类
public class InventoryItem
{
//物品ID
public int ItemId;
//个数
public int Count=1;
}
//背包管理类
public class InventoryManager//普通类
{
private static InventoryManager instance;
public static InventoryManager Instance
{get{
if(instance==null){
instance = new InventoryManager();
}
return instance;
}
}
//背包
public List Inventory = new List();
//添加物品
public void AddItem(int ItemId,int count = 1){
//查看背包中是否存在该物品
foreach(InventoryItem tmp in Inventory){
if(tmp.ItemId == ItemId){
tmp.Count += count;
return;
}
}
//背包中不存在该物品
InventoryItem item = new InventoryItem();
item.ItemId = ItemId;
item.Count = Count;
Inventory.Add(item);
return;
}
//获得物品
public InventoryItem GetItem(int itemid){
foreach(InventoryItem item in Inventory){
if(item.ItemId == itemid){
return item;
}
}
return null;
}
//删除物品
public void RemoveItem(int itemid,int count = 1){//count:移除多少个
for(int i=0;i<Inventory.Count;i++){
InventoryItem i = Inventory[i];
if(item.Itemid == itemid && item.Count>0){
item.Count -= count;
if(item.Count<=0){
Inventory.Remove(item);
}
}
}
}
}