背包系统:
** 首先我们得分析背包的组成:一个背包系统有一个背包的背景UI以及格子UI和物品UI 组成差不多我们就得写三个类,代码量比较大就是物品类!**
我们先创建好预制体
UI设置好了之后就是开始写脚本
InventoryPanel.cs
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class InventotyInfo
{
public int id;
public int num;
public int index;
public int Id
{
get {
return id; }
set {
id = value; }
}
public int Num
{
get {
return num; }
set {
num = value; }
}
public int Index
{
get {
return index; }
set {
index = value; }
}
public void AddNum(int number)
{
num += number;
}
}
public class InventoryPanel : BasePanel
{
public static InventoryPanel instance;
public Button closeButton;
public Button arrangeBtton;
public Transform front;
private SlotItem[] slots ;
//背包信息
public List<InventotyInfo> inventotyInfos=new List<InventotyInfo>();
//背包临时信息
public List<InventotyInfo> tempInventoryInfos = new List<InventotyInfo>();
public Button queryButton01;
public Button queryButton02;
public Button queryButton03;
private void Awake()
{
instance = this;
slots = transform.GetChild(1).GetChild(2).GetComponentsInChildren<SlotItem>();
for (int i = 0; i < slots.Length; i++)
{
slots[i].index = i;
slots[i].isItem = false;
}
}
// Start is called before the first frame update
void Start()
{
inventotyInfos = GameObject.Find("MainMenuPanel").GetComponent<MainMenuPanel>().GetInventory();
if(inventotyInfos.Count>0)
{
ShowAllGoods();
}
tempInventoryInfos= GameObject.Find("MainMenuPanel").GetComponent<MainMenuPanel>().GetBuyInventory();
if(tempInventoryInfos!=null)
{
foreach (var info in tempInventoryInfos)
{
IncreaseGoods(info.id, info.num);
}
GameObject.Find("MainMenuPanel").GetComponent<MainMenuPanel>().CleanBuyInventory();
}
closeButton?.onClick.AddListener(() =>
{
Destroy(this.gameObject);
MainMenuPanel mainMenuPanel= GameObject.Find("MainMenuPanel").GetComponent<MainMenuPanel>();
mainMenuPanel.SetUIPanelState();
mainMenuPanel.SetInventory(inventotyInfos);
});
arrangeBtton?.onClick.AddListener(() =>
{
ArrangeAllIsItemSlot();
});
queryButton01.onClick.AddListener(() =>
{
CleanSlotInfo();
QueryInventory(1001);
})