学习游制作记录(背包UI以及各种物品的存储)8.12
1.创建物品槽
ItemObject脚本:
private void OnValidate()//这个函数可以在非运行状态更改对象的属性
{
GetComponent<SpriteRenderer>().sprite=itemData.icon;//直接可以看到物品的图标
gameObject.name ="Item Object -"+itemData.ItemName;//修改名字
}
创建一个画布,在画布下再建一个图像UI,在图像UI下创建一个文本UI,设置文本在图像的右下角,且偏右显示
创建UI_ItemSlot脚本挂载在图像UI上:
[SerializeField] private Image image;//图像和文本
[SerializeField] private TextMeshProUGUI textMeshPro;
public InventoryItem Item;//物品数据
void Start()
{
if(Item != null)//初始化图像和数量
{
image.sprite = Item.data.icon;
}
if(Item.stackSize>1)
{
textMeshPro.text =Item.stackSize.ToString();
}
else
{
textMeshPro.text = " ";
}
}
2.实现背包里存放物品并排序显示
UI_ItemSlot脚本:
public void UpdataSlot(InventoryItem _newItem)//传入物品类
{
Item = _newItem;
image.color = Color.white;//没有物品时槽是透明的
if (Item != null)
{
image.sprite = Item.data.icon;
}
if (Item.stackSize > 1)
{
textMeshPro.text = Item.stackSize.ToString();
}
else
{
textMeshPro.text = " ";
}
}
Inventory脚本:
为所有物品槽创建一个父对象,并给它挂载Gird layout Group组件,它可以自然分配子物体的位置
[Header("Inventory UI")]
[SerializeField] private Transform InventorySlotParent;//槽位的父对象
private UI_ItemSlot[] itemSlot;//物品槽的数组
private void UpdataSlotUI()//在添加和减少的函数里调用
{
for (int i = 0; i < inventoryItems.Count; i++)//检查列表所有物品类
{
itemSlot[i].UpdataSlot(inventoryItems[i]);
}
}
3.实现装备类的物品数据
ItemData脚本:
public enum ItemType//第一个分类——材料与装备
{
Material,
Equipment
}
创建ItemData_Equipment脚本:
public enum EquiomentType //装备的分类——武器,护甲,饰品和药水
{
Weapon,
Armor,
Amulet,
Flask
}
[CreateAssetMenu(fileName = "New Item Data", menuName = "Data/Equipment")]
public class ItemData_Equipment : ItemData
{
public EquiomentType equipmentType;
}
利用上述脚本创建几个物品
4.实现分类存储
将装备和材料分开存储
Inventory脚本:
[SerializeField] public List<InventoryItem> stash;//仿照之前的方法重写一遍即可
public Dictionary<ItemData,InventoryItem> stashItemsDictionary;
[SerializeField] private Transform stashSlotParent;
private UI_ItemSlot[] stashSlot;
private void UpdataSlotUI()
{
for (int i = 0; i < inventory.Count; i++)
{
itemSlot[i].UpdataSlot(inventory[i]);
}
for(int i = 0;i< stash.Count;i++)//更新材料的存储
{
stashSlot[i].UpdataSlot(stash[i]);
}
}
public void AddItem(ItemData _item)
{
if (_item.itemType == ItemType.Equipment)
{
AddToInventory(_item);
}
else if( _item.itemType == ItemType.Material)
{
AddToStash(_item);//添加方法与之前类似,这里不作赘述
}
UpdataSlotUI();
}
public void RemoveItem(ItemData _item)//移除同理
{
if (_item.itemType == ItemType.Equipment)
{
RemoveInventory(_item);
}
else if( _item.itemType == ItemType.Material)
{
RemoveStash(_item);
}
UpdataSlotUI();
}
只需要再创建一个槽位的父对象即可