1存儲:遍歷整個背包的格子。將有子物體的格子給儲存下來
public void SaveInventory()
{
StringBuilder sb = new StringBuilder();
foreach (Slot slot in slotList)
{
if (slot.transform.childCount > 0)
{
ItemUI itemUI = slot.transform.GetChild(0).GetComponent<ItemUI>();
sb.Append(itemUI.Item.ID + ","+itemUI.Amount+"-");
}
else
{
sb.Append("0-");
}
}
PlayerPrefs.SetString(this.gameObject.name, sb.ToString());
}
2加載:
public void LoadInventory()
{
if (PlayerPrefs.HasKey(this.gameObject.name) == false) return;
string str = PlayerPrefs.GetString(this.gameObject.name);
//print(str);
string[] itemArray = str.Split('-');
for (int i = 0; i < itemArray.Length-1; i++)
{
string itemStr = itemArray[i];
if (itemStr != "0")
{
//print(itemStr);
string[] temp = itemStr.Split(',');
int id = int.Parse(temp[0]);
Item item = InventoryManager.Instance.GetItemById(id);
int amount = int.Parse(temp[1]);
for (int j = 0; j < amount; j++)
{
slotList[i].StoreItem(item);
}
}
}
}