evershade/Assets/Scripts/Controllers/ToolbarUIController.cs

128 lines
3.5 KiB
C#

using System.Collections;
using System.Collections.Generic;
using Managers;
using UnityEngine;
// InventoryUI.cs
public class ToolbarUIController : MonoBehaviour
{
public static ToolbarUIController Instance;
public Transform itemParent;
private readonly Dictionary<int, SlotComponent> _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.Instance.Slots.Count == 0)
ToolbarManager.Instance.Initialize(PlayerManager.Instance.playerData);
ToolbarManager.Instance.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.Instance.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.Instance.SetActiveSlot(slotId);
Debug.Log("Slot clicked: " + slotId + " / Set Active");
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.Instance.GetSlotPrefab();
foreach (var toolbarSlot in ToolbarManager.Instance.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<SlotComponent>();
var slotHandler = slotDisplay.GetComponent<SlotHandler>();
slotHandler.OnSlotClicked.AddListener(() => OnSlotClicked(i));
Debug.Log("Added slot handler to slot: " + i);
// Add prefab to slot
slotComponent.SetSlotDetails(toolbarSlot.Value);
slotComponent.SetSlotActive(false);
slotComponent.SetSlotType(Slot.SlotType.Toolbar);
slotComponent.SetSlotId(i);
_slots.Add(i, slotComponent);
}
}
}