using UnityEngine; using UnityEngine.UI; using TMPro; using Unity.Netcode; using System.Collections.Generic; public class QuickslotUI : MonoBehaviour { [Header("Dynamic Setup")] [SerializeField] private GameObject slotPrefab; // 생성할 슬롯 프리팹 [SerializeField] private Transform slotContainer; // 슬롯들이 들어갈 부모 (HotbarPanel) [Header("Weight UI")] [SerializeField] private Slider weightSlider; [SerializeField] private TextMeshProUGUI weightText; private List _uiSlots = new List(); private PlayerInventory _linkedInventory; public void BindInventory(PlayerInventory inventory) { _linkedInventory = inventory; // 1. 기존에 있던 슬롯 UI들 모두 삭제 (초기화) foreach (Transform child in slotContainer) Destroy(child.gameObject); _uiSlots.Clear(); // 2. 인벤토리 데이터 크기(slotCount)만큼 UI 프리팹 생성 for (int i = 0; i < _linkedInventory.slotCount; i++) { GameObject newSlot = Instantiate(slotPrefab, slotContainer); InventorySlotUI slotUI = newSlot.GetComponent(); _uiSlots.Add(slotUI); } // 3. 이벤트 등록 및 초기 갱신 _linkedInventory.Slots.OnListChanged += (e) => RefreshAll(); RefreshAll(); } private void RefreshAll() { if (_linkedInventory == null) return; for (int i = 0; i < _uiSlots.Count; i++) { var data = _linkedInventory.Slots[i]; _uiSlots[i].UpdateView(data.ItemID, data.Amount); } UpdateWeightDisplay(); } // 데이터 변경 이벤트 핸들러 private void OnInventoryDataChanged(NetworkListEvent changeEvent) { RefreshAll(); } private void UpdateWeightDisplay() { if (_linkedInventory == null) return; float current = _linkedInventory.CurrentWeight; float max = _linkedInventory.maxWeight; if (weightSlider != null) weightSlider.value = current / max; if (weightText != null) weightText.text = $"{current:F1} / {max:F1} kg"; } private void OnDestroy() { // 이벤트 구독 해제 (메모리 누수 방지) if (_linkedInventory != null) _linkedInventory.Slots.OnListChanged -= OnInventoryDataChanged; } }