昨天心态有点炸,一个一个游戏在我电脑里打包,并没有选择developer,在我电脑上右下角也没有developer build结果在其他人电脑上会显示,搞了半天原来是版本问题-.-
做一个装备的预制体,一个image用来显示物体图片,一个image用来显示数字,添加一个ItemUI脚本用来更改信息。
itemUI:
public Item Item { get; set; } public int Amount { get; set; } private Image itemImage; private Text amountText; private Image ItemImage { get { if(itemImage==null) { itemImage = GetComponent<Image>(); } return itemImage; } } private Text AmountText { get { if (amountText == null) { amountText = GetComponentInChildren<Text>(); } return amountText; } }再给每个小格子(slot)肯定要管理他下面的子物体(这个格子放的物体,也就是上面的预制体),用来获取更新当前格子内物体的数量和种类。
Slot
public GameObject itemPrefab; /// <summary> /// 把item放在自身下面 /// 如果下面有了就 amout++ /// 没有就根据itemPrefab实例化item /// </summary> /// <param name="item"></param> public void StoreItem(Item item) { if(transform.childCount==0) { GameObject itemGameObject= Instantiate(itemPrefab) as GameObject; itemGameObject.transform.SetParent(this.transform); itemGameObject.transform.localPosition = Vector3.zero; itemGameObject.GetComponent<ItemUI>().SetItem(item, 1); } else { transform.GetChild(0).GetComponent<ItemUI>().AddAmount(1); } } /// <summary> /// 得到已有物品的格子身上的物品类型 /// </summary> public Item.ItemType GetItemType() { return transform.GetChild(0).GetComponent<ItemUI>().Item.Type; } public int GetItemId() { return transform.GetChild(0).GetComponent<ItemUI>().Item.ID; } public bool IsFilled() { ItemUI itemUI = transform.GetChild(0).GetComponent<ItemUI>(); return itemUI.Amount >= itemUI.Item.Capacity;//大于等于当前容量 }slot有很多,因此需要一个类集中管理,建立一个Inventory类管理所有格子
Inventory:
protected Slot[] slotList;//物品格子 public virtual void Start() { slotList= GetComponentsInChildren<Slot>(); } /// <summary> /// 通过ID获取 /// </summary> /// <returns></returns> public bool StoreItem(int id) { Item item = InventoryManager.Instance.GetItemById(id); return StoreItem(item); } public bool StoreItem(Item item) { if(item==null) { Debug.LogWarning("要存储的物品不存在"); return false; } //物品是否可以叠加 if (item.Capacity==1) { //TODO Slot slot= FindEmptySlot(); if(slot==null) { Debug.LogWarning("没有空的物品槽"); }else { //存储物品 slot.StoreItem(item); } } else { //先判断是否存在相同的slot Slot slot = FindSameIdSlot(item); if(slot!=null) { //如果找到了 slot.StoreItem(item); } else//如果没找到 { Slot slots = FindEmptySlot(); if(slots!=null) { slots.StoreItem(item); } else { //没空间 Debug.LogError("没有空的物品槽"); return false; } } } return true; } /// <summary> /// 寻找空格子 /// </summary> private Slot FindEmptySlot() { foreach(Slot slot in slotList) { //此时没有子物体 if(slot.transform.childCount==0) { return slot; } } return null; } /// <summary> /// 寻找相同类型的物品槽 /// </summary> /// <returns></returns> private Slot FindSameIdSlot(Item item) { foreach(Slot slot in slotList) { //首先判断格子是不是空,不是空说明才有东西&&类型一样&&没满 if(slot.transform.childCount>=1&&slot.GetItemId()==item.ID&&slot.IsFilled()==false) { return slot; } } return null; }