using UnityEngine;
using System.Collections;
using System.Text;
public class Inventory : MonoBehaviour {
protected Slot[] slotArray;
private CanvasGroup canvasGroup;
private float targetA = 0;
private float smothing = 6;
public virtual void Start()
{
slotArray = GetComponentsInChildren<Slot>();
canvasGroup = GetComponent<CanvasGroup>();
}
void Update()
{
if (canvasGroup.alpha != targetA)
{
canvasGroup.alpha = Mathf.Lerp(canvasGroup.alpha, targetA, smothing * Time.deltaTime);
if (Mathf.Abs(canvasGroup.alpha - targetA) < 0.01f)
{
canvasGroup.alpha = targetA;
}
}
}
public bool AddItem(int id)
{
ItemBase item = InventoryManager.Instance.GetItemById(id);
return AddItem(item);
}
public bool AddItem(ItemBase item)
{
if (item == null)
{
Debug.Log("你增加的物品ID不存在");
return false;
}
if (item.maxStack == 1) //叠加数量为1,所以给他找一个空的物品槽
{
Slot emptySlot = FindEmptySlot();
if (emptySlot == null)
{
Debug.Log("物品栏中的槽已经满了,不能再增加物品了");
return false;
}
else
{
emptySlot.AddItem(item);
}
}
else
{
Slot slot = FindSameTypeSlot(item);
if (slot!= null)
{
slot.AddItem(item);
}
else
{
Slot emptySlot = FindEmptySlot();
if(emptySlot!=null){
emptySlot.AddItem(item);
}
else
{
Debug.Log("物品栏中的槽已经满了,不能再增加物品了");
return false;
}
}
}
return true;
}
private Slot FindEmptySlot()
{
foreach (Slot slot in slotArray)
{
if (slot.transform.childCount == 0)
{
return slot;
}
}
return null;
}
private Slot FindSameTypeSlot(ItemBase item)
{
foreach (Slot slot in slotArray)
{
if ((slot.transform.childCount >=1)&&slot.GetThisItemID()==item.ID&&slot.isFull()==false)
{
return slot;
}
}
return null;
}
public void DisplaySwitch()
{
if (targetA==0)
{
targetA = 1;
canvasGroup.blocksRaycasts = true;
}
else
{
targetA = 0;
canvasGroup.blocksRaycasts = false;
}
}
public void SaveInventory() //频繁的更改字符用stringbuilder
{
StringBuilder sb = new StringBuilder();
foreach (Slot slot in slotArray)
{
if (slot.transform.childCount > 0)
{
Item itemUI = slot.transform.GetChild(0).GetComponent<Item>();
sb.Append(itemUI.itemBase.ID + "," + itemUI.Amount+"-");
}
else
{
sb.Append("0-");
}
}
PlayerPrefs.SetString(this.gameObject.name, sb.ToString());
}
public void LoadInventory()
{
if (PlayerPrefs.HasKey(this.gameObject.name))
{
string str = PlayerPrefs.GetString(this.gameObject.name);
string[] itemArray = str.Split('-');
for (int i = 0; i < itemArray.Length-1; i++)
{
string s = itemArray[i];
if (s != "0")
{
string[] temp = s.Split(',');
int id = int.Parse(temp[0]);
int amount = int.Parse(temp[1]);
ItemBase itemInfo=InventoryManager.Instance.GetItemById(id);
slotArray[i].AddItem(itemInfo);
slotArray[i].GetComponentInChildren<Item>().SetAmount(amount);
}
}
}
}
}
UGUI--背包系统之二--------Inventory
最新推荐文章于 2018-09-14 09:19:25 发布