JinChanChan/Assets/Scripts/BeiBao/View/BeiBaoView.cs

70 lines
2.2 KiB
C#

using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace BeiBao.View
{
public class BeiBaoView : MonoBehaviour
{
public TMP_InputField nameText;
public TMP_InputField idText;
public TMP_InputField countText;
public Button Add;
public GameObject itemPfb;
Inventory inventory;
List<BeiBaoItem> items = new List<BeiBaoItem>();
private void Awake()
{
inventory = new Inventory(5);
for (var i = 0; i < inventory.SlotCount; i++)
{
var instantiate = GameObject.Instantiate(itemPfb, itemPfb.transform.parent);
instantiate.gameObject.SetActive(true);
var beiBaoItem = instantiate.GetComponent<BeiBaoItem>();
beiBaoItem.Refresh(inventory.Slots[i]);
items.Add(beiBaoItem);
}
inventory.RefreshInventorySlot += Refresh;
Add.onClick.AddListener(ClickAdd);
}
private void ClickAdd()
{
var count = int.Parse(countText.text);
var id = int.Parse(idText.text);
if (count > 0)
{
// 创建物品
Item healthPotion = new Item(nameText.text, id, 99);
// 添加物品到背包
var b = inventory.AddItem(healthPotion, count, out var restCount);
if (!b)
{
Debug.Log($"添加失败!还有 {restCount} 个 {healthPotion.ItemName} 未添加,背包没位置放了,放不了一点");
}
}
else if (count < 0)
{
var b = inventory.RemoveItem(id, Mathf.Abs(count),out var restCount);
if (!b)
{
Debug.Log($"取出失败!还有 {restCount} 个 {id} 未取出,背包没有东西了,取不了一点");
}
}
}
void Refresh(IReadOnlyList<InventorySlot> slot)
{
for (var i = 0; i < slot.Count; i++)
{
items[i].Refresh(slot[i]);
}
}
}
}