using UnityEngine; using UnityEngine.UI; public class InventoryUI : MonoBehaviour { public RectTransform content; public Text outputText; public Font uiFont; public Color textColor = new Color(0.92f, 0.9f, 0.82f); private float refreshTimer; private string lastSignature; private void OnEnable() { Subscribe(); Refresh(); } private void Start() { Subscribe(); Refresh(); } private void OnDisable() { if (Inventory.Instance != null) { Inventory.Instance.OnInventoryChanged -= Refresh; } } private void Update() { refreshTimer -= Time.unscaledDeltaTime; if (refreshTimer > 0f) { return; } refreshTimer = 0.25f; Subscribe(); string signature = BuildSignature(); if (signature != lastSignature) { lastSignature = signature; Refresh(); } } private void Subscribe() { if (Inventory.Instance != null) { Inventory.Instance.OnInventoryChanged -= Refresh; Inventory.Instance.OnInventoryChanged += Refresh; } } public void Refresh() { if (outputText != null) { outputText.text = BuildDisplayText(); return; } if (content == null) { return; } ClearContent(); if (Inventory.Instance == null || Inventory.Instance.Slots.Count == 0) { CreateLine("Пусто"); return; } foreach (Inventory.InventorySlot slot in Inventory.Instance.Slots) { if (slot.item == null) { continue; } CreateLine($"{slot.item.itemName} x{slot.amount}"); } } private string BuildDisplayText() { if (Inventory.Instance == null || Inventory.Instance.Slots.Count == 0) { return "Пусто"; } System.Text.StringBuilder builder = new System.Text.StringBuilder(); foreach (Inventory.InventorySlot slot in Inventory.Instance.Slots) { if (slot.item == null) { continue; } builder.AppendLine($"{slot.item.itemName} x{slot.amount}"); } return builder.Length > 0 ? builder.ToString().TrimEnd() : "Пусто"; } private string BuildSignature() { if (Inventory.Instance == null) { return "inventory:null"; } System.Text.StringBuilder builder = new System.Text.StringBuilder(); foreach (Inventory.InventorySlot slot in Inventory.Instance.Slots) { if (slot.item == null) { continue; } builder.Append(slot.item.itemId).Append(':').Append(slot.amount).Append('|'); } return builder.ToString(); } private void ClearContent() { for (int i = content.childCount - 1; i >= 0; i--) { Destroy(content.GetChild(i).gameObject); } } private void CreateLine(string value) { GameObject line = new GameObject("Inventory Line", typeof(RectTransform), typeof(Text)); line.transform.SetParent(content, false); Text text = line.GetComponent(); text.font = uiFont != null ? uiFont : Resources.GetBuiltinResource("Arial.ttf"); text.fontSize = 16; text.color = textColor; text.text = value; RectTransform rect = line.GetComponent(); rect.sizeDelta = new Vector2(0f, 24f); } }