using System; using Base; using Entity; using UnityEngine; namespace UI { /// /// 装备UI类,负责显示当前聚焦角色的装备(物品栏中的前三个槽位)。 /// public class EquipmentUI : MonoBehaviour,ITick { // 这些公共变量用于在 Inspector 中分配 ItemUI 对象,分别对应当前使用、第二个和第三个装备槽。 public ItemUI currentUse; // 当前正在使用的装备槽 UI public ItemUI two; // 角色物品栏中的第二个槽位对应的 UI public ItemUI three; // 角色物品栏中的第三个槽位对应的 UI // 存储当前聚焦的实体(通常是玩家角色)。 private Character focusedEntity; private void Start() { // 订阅 Program 实例的聚焦实体改变事件,以便在聚焦实体变化时更新 UI。 Program.Instance.OnFocusedEntityChanged += FocusEntityChanged; // 组件启动时初始化 UI 显示。 UpdateUI(); Clock.AddTick(this); } private void OnDestroy() { // 在销毁时取消订阅事件,防止内存泄漏。 // 检查 Program.Instance 是否仍然存在,以避免在场景销毁时出现空引用异常。 if (Program.Instance != null) { Program.Instance.OnFocusedEntityChanged -= FocusEntityChanged; } // 如果聚焦实体及其背包存在,则取消订阅背包改变事件。 if (focusedEntity != null && focusedEntity.Inventory != null) { focusedEntity.Inventory.OnInventoryChanged -= UpdateUI; } Clock.RemoveTick(this); } public void Tick() { if (!focusedEntity) return; if (Input.GetKeyDown(KeyCode.Alpha1)) { } else if(Input.GetKeyDown(KeyCode.Alpha2)) { focusedEntity.CurrentSelected = focusedEntity.CurrentSelected == 0 ? 1 : 0; UpdateUI(); } else if(Input.GetKeyDown(KeyCode.Alpha3)) { focusedEntity.CurrentSelected = focusedEntity.CurrentSelected == 2 ? 1 : 2; UpdateUI(); } } /// /// 当聚焦实体发生改变时调用此方法。 /// /// 新的聚焦实体。 private void FocusEntityChanged(Entity.Entity e) { // 如果存在旧的聚焦实体,则先取消订阅其背包改变事件。 if (focusedEntity) { focusedEntity.Inventory.OnInventoryChanged -= UpdateUI; } // 设置新的聚焦实体,并尝试将其转换为 Character 类型。 focusedEntity = e as Character; // 如果新的聚焦实体存在且是 Character 类型,则订阅其背包改变事件。 if (focusedEntity) { focusedEntity.Inventory.OnInventoryChanged += UpdateUI; } // 聚焦实体改变后更新 UI 显示。 UpdateUI(); } /// /// 更新装备 UI 的显示。 /// 根据聚焦角色的当前选中物品和物品栏状态来更新UI。 /// public void UpdateUI() { if (focusedEntity) { var currentSelectedIndex = focusedEntity.CurrentSelected; var nonCurrentUseCounter = 0; // 用于计数非当前选中项的索引,以分配给 two 和 three // 遍历角色的前三个装备槽(假设物品栏只显示前3个槽位)。 for (var i = 0; i < 3; i++) { var slot = focusedEntity.Inventory.GetSlot(i); if (i == currentSelectedIndex) { // 如果是当前选中的槽位,则将物品信息显示在 currentUse UI 上。 currentUse.SetDisplayItem(slot); } else { // 如果不是当前选中的槽位,则根据计数器决定显示在 two 或 three UI 上。 if (nonCurrentUseCounter == 0) { two.SetDisplayItem(slot); } else if (nonCurrentUseCounter == 1) { three.SetDisplayItem(slot); } nonCurrentUseCounter++; } } } else { // 如果没有聚焦的实体,则清空所有装备槽的 UI 显示。 currentUse.SetDisplayItem(null); two.SetDisplayItem(null); three.SetDisplayItem(null); } } } }