using System.Collections; using System.Collections.Generic; using UnityEngine; // InventoryUI.cs public class ToolbarUIController : MonoBehaviour { public static ToolbarUIController Instance; public Transform itemParent; public ToolbarManager toolbarManager; public PrefabManager prefabManager; private readonly Dictionary _slots = new(); private void Awake() { // Implement singleton pattern if (Instance == null) Instance = this; else Destroy(gameObject); } private void Start() { Debug.Log("ToolbarUI Start"); if (itemParent == null) { Debug.LogWarning("ItemParent is null! Can not attach"); return; } // Delete existing children if any. foreach (Transform child in itemParent) Destroy(child.gameObject); if (toolbarManager.Slots.Count == 0) toolbarManager.InitializeToolbar(); toolbarManager.OnActiveSlotChanged += UpdateActiveSlot; var updateUI = UpdateUI(); StartCoroutine(updateUI); Debug.Log("Finished adding items to toolbar slots"); } public void ListChildren(GameObject parent) { foreach (Transform child in parent.transform) Debug.Log("Child: " + child.name); } public void UpdateActiveSlot() { // Update the active slot in the UI Debug.Log("Updating active slot in UI"); // set all slots to inactive foreach (var slot in _slots) { Debug.Log("Setting slot to inactive:" + slot.Key); slot.Value.SetSlotActive(false); } // set active slot to active var activeSlot = toolbarManager.ActiveSlot.slotId; var activeSlotComponent = _slots[activeSlot]; activeSlotComponent.SetSlotActive(true); } public void RemoveSlot(int slotId) { if (_slots.TryGetValue(slotId, out var slot)) { Destroy(slot); _slots.Remove(slotId); } } public void OnSlotClicked(int slotId) { toolbarManager.SetActiveSlot(slotId); UpdateActiveSlot(); } public IEnumerator UpdateUI() { // clear all existing slots foreach (var slot in _slots.Values) Destroy(slot); _slots.Clear(); // Wait until the next frame before recreating the slots yield return null; // Get values from inventory and redraw the inventory slots based on that. var slotPrefab = prefabManager.GetSlotPrefab(); foreach (var toolbarSlot in toolbarManager.Slots) { // Draw slots to screen var slotDisplay = Instantiate(slotPrefab, itemParent); slotDisplay.transform.localScale = new Vector3(1, 1, 1); var i = toolbarSlot.Key; var slotComponent = slotDisplay.GetComponent(); var slotHandler = slotDisplay.GetComponent(); slotHandler.OnSlotClicked.AddListener(() => OnSlotClicked(i)); Debug.Log("Added slot handler to slot: " + i); // Add prefab to slot slotComponent.SetSlotDetails(toolbarSlot.Value); _slots.Add(i, slotComponent); } } }