118 lines
3.1 KiB
C#
118 lines
3.1 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class HotbarUI : MonoBehaviour
|
|
{
|
|
public Inventory inventory;
|
|
public ItemUseSystem itemUseSystem;
|
|
public Transform slotContainer;
|
|
public GameObject slotPrefab;
|
|
public int slotCount = 10;
|
|
|
|
private readonly List<GameObject> views = new List<GameObject>();
|
|
|
|
private void OnEnable()
|
|
{
|
|
if (inventory != null)
|
|
{
|
|
inventory.OnInventoryChanged += RefreshUI;
|
|
}
|
|
|
|
if (itemUseSystem != null)
|
|
{
|
|
itemUseSystem.OnSelectionChanged += RefreshUI;
|
|
}
|
|
|
|
BuildSlots();
|
|
RefreshUI();
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
if (inventory != null)
|
|
{
|
|
inventory.OnInventoryChanged -= RefreshUI;
|
|
}
|
|
|
|
if (itemUseSystem != null)
|
|
{
|
|
itemUseSystem.OnSelectionChanged -= RefreshUI;
|
|
}
|
|
}
|
|
|
|
public void BuildSlots()
|
|
{
|
|
ClearSlots();
|
|
if (slotContainer == null || slotPrefab == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
for (int i = 0; i < slotCount; i++)
|
|
{
|
|
GameObject view = Instantiate(slotPrefab, slotContainer);
|
|
view.SetActive(true);
|
|
int capturedIndex = i;
|
|
|
|
Button button = view.GetComponent<Button>();
|
|
if (button != null && itemUseSystem != null)
|
|
{
|
|
button.onClick.AddListener(() => itemUseSystem.SelectSlot(capturedIndex));
|
|
}
|
|
|
|
views.Add(view);
|
|
}
|
|
}
|
|
|
|
public void RefreshUI()
|
|
{
|
|
for (int i = 0; i < views.Count; i++)
|
|
{
|
|
GameObject view = views[i];
|
|
InventorySlot slot = inventory != null ? inventory.GetSlot(i) : null;
|
|
|
|
Text label = view.transform.Find("Label")?.GetComponent<Text>();
|
|
if (label != null)
|
|
{
|
|
label.text = slot != null ? slot.item.itemName + "\nx" + slot.amount : "Пусто";
|
|
}
|
|
|
|
Text number = view.transform.Find("Number")?.GetComponent<Text>();
|
|
if (number != null)
|
|
{
|
|
number.text = i == 9 ? "0" : (i + 1).ToString();
|
|
}
|
|
|
|
Image marker = view.transform.Find("ColorMarker")?.GetComponent<Image>();
|
|
if (marker != null)
|
|
{
|
|
marker.color = slot != null ? slot.item.itemColor : new Color(0.18f, 0.20f, 0.22f, 1f);
|
|
}
|
|
|
|
Image background = view.GetComponent<Image>();
|
|
if (background != null)
|
|
{
|
|
bool selected = itemUseSystem != null && itemUseSystem.selectedSlotIndex == i;
|
|
background.color = selected
|
|
? new Color(0.82f, 0.66f, 0.30f, 0.96f)
|
|
: new Color(0.10f, 0.12f, 0.15f, 0.92f);
|
|
}
|
|
}
|
|
}
|
|
|
|
public void ClearSlots()
|
|
{
|
|
views.Clear();
|
|
if (slotContainer == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
for (int i = slotContainer.childCount - 1; i >= 0; i--)
|
|
{
|
|
Destroy(slotContainer.GetChild(i).gameObject);
|
|
}
|
|
}
|
|
}
|