Unity3D 游戏开发:制作游戏背包 显示控制(27)

563 阅读1分钟

一、开发操作

1、修改Image名称,添加Button组件

image.png

2、Bag UI赋值

image.png

3、添加On Click事件

image.png

二、脚本编程

1、修改Inventory UI.cs文件,实现显示、关闭事件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MFarm.Inventory 
{
    public class InventoryUI : MonoBehaviour
    {
        [Header("玩家背包")]
        [SerializeField] private GameObject bagUI;
        [SerializeField] private SlotUI[] playerSlots;

        private bool bagOpened;
        private void OnEnable()
        {
            EventHandler.UpdateInventoryUI += OnUpdateInventoryUI;
        }
        private void OnDisable()
        {
            EventHandler.UpdateInventoryUI -= OnUpdateInventoryUI;
        }

        private void Start()
        {
            for (int i = 0; i < playerSlots.Length; i++)
            {
                playerSlots[i].slotIndex = i; 
            }
            bagOpened = bagUI.activeInHierarchy;
        }


        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.B))
            {
                OpenBagUI();
            }
        }
        private void OnUpdateInventoryUI(InventoryLocation location, List<InventoryItem> list)
        {
            switch (location)
            {
                case InventoryLocation.Player:
                    for (int i = 0; i < playerSlots.Length; i++)
                    {
                        if (list[i].itemAmount > 0)
                        {
                            var item = InventoryManager.Instance.GetItemDetails(list[i].itemID);

                            playerSlots[i].UpdateSlot(item, list[i].itemAmount);
                        }
                        else
                        {
                            playerSlots[i].UpdateEmptySlot();
                        }

                    }
                    break;
            }
        }

        public void OpenBagUI()
        {
            bagOpened = !bagOpened;

            bagUI.SetActive(bagOpened);
        }
    }
}


三、脚本逻辑

未完待续......

阅读更多作者文章:

Unity3D 游戏开发:制作游戏背包 物品栏UI显示(26)