65 lines
2.5 KiB
C#
65 lines
2.5 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
// ============================================================================
|
|
// WeaponInventory (UI)
|
|
// ----------------------------------------------------------------------------
|
|
// 무기 인벤토리 화면 표시 — 표시 전용 (무기 교체는 1/2/3 키로).
|
|
//
|
|
// 이 클래스는 무기 목록을 "소유하지 않는다". 데이터의 단일 진실은
|
|
// PlayerWeaponInventory이고, 이 UI는 그걸 구독해서 그림만 그린다.
|
|
// - OnInventoryChanged 이벤트를 받으면 슬롯을 다시 그림
|
|
// - 현재 장착 무기 슬롯에 하이라이트 표시
|
|
//
|
|
// _slots는 데이터가 아니라 생성한 화면 오브젝트 캐시일 뿐 (재사용 풀).
|
|
// ============================================================================
|
|
public class WeaponInventory : MonoBehaviour
|
|
{
|
|
[SerializeField] private PlayerWeaponInventory _wInvenSource; // 비워두면 런타임에 자동 탐색
|
|
[SerializeField] private Transform _slotRoot; // 슬롯이 생성될 부모
|
|
[SerializeField] private WeaponSlot _slotPrefab; // 슬롯 프리팹
|
|
|
|
// 생성된 슬롯 UI 캐시. 무기 수가 늘면 추가 생성하고, 남는 슬롯은 비활성화.
|
|
private readonly List<WeaponSlot> _slots = new();
|
|
|
|
private void Start()
|
|
{
|
|
if (_wInvenSource == null)
|
|
_wInvenSource = FindFirstObjectByType<PlayerWeaponInventory>();
|
|
|
|
if (_wInvenSource != null)
|
|
_wInvenSource.OnInventoryChanged += Refresh;
|
|
|
|
Refresh();
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
if (_wInvenSource != null)
|
|
_wInvenSource.OnInventoryChanged -= Refresh;
|
|
}
|
|
|
|
|
|
// 인벤토리 상태를 화면에 반영. 슬롯 개수를 무기 수에 맞추고 내용/하이라이트 갱신.
|
|
private void Refresh()
|
|
{
|
|
if (_wInvenSource == null || _slotRoot == null || _slotPrefab == null) return;
|
|
|
|
IReadOnlyList<WeaponData> weapons = _wInvenSource.Weapons;
|
|
|
|
// 슬롯이 모자라면 생성 (한 번 만든 슬롯은 재사용 — GC 최소화).
|
|
while (_slots.Count < weapons.Count)
|
|
_slots.Add(Instantiate(_slotPrefab, _slotRoot));
|
|
|
|
for (int i = 0; i < _slots.Count; i++)
|
|
{
|
|
bool used = i < weapons.Count;
|
|
_slots[i].gameObject.SetActive(used);
|
|
if (!used) continue;
|
|
|
|
_slots[i].SetWeapon(weapons[i]);
|
|
_slots[i].SetSelected(i == _wInvenSource.CurrentIndex);
|
|
}
|
|
}
|
|
}
|