Files
ProjectMD/Assets/Scripts/Player/PlayerEquipmentHandler.cs
Dal4segno db5db4b106 코드 리팩토링
재사용성 및 확장성을 고려하여 코드 전반을 리팩토링함
2026-01-21 01:45:15 +09:00

125 lines
3.3 KiB
C#

using Unity.Netcode;
using UnityEngine;
/// <summary>
/// Handles equipment visuals for the player.
/// Uses the new EquipmentSlot system while maintaining backwards compatibility.
/// </summary>
public class PlayerEquipmentHandler : NetworkBehaviour
{
[Header("Equipment Settings")]
[SerializeField] private Transform mainHandAnchor;
[SerializeField] private Transform offHandAnchor;
[Header("Slot Configuration")]
[SerializeField] private EquipmentSlot mainHandSlot;
private PlayerInventory _inventory;
private GameObject _currentToolInstance;
void Awake()
{
_inventory = GetComponent<PlayerInventory>();
// Initialize main hand slot if not configured in inspector
if (mainHandSlot == null)
{
mainHandSlot = new EquipmentSlot
{
SlotType = EquipmentSlotType.MainHand,
AttachPoint = mainHandAnchor
};
}
else if (mainHandSlot.AttachPoint == null)
{
mainHandSlot.AttachPoint = mainHandAnchor;
}
}
public override void OnNetworkSpawn()
{
// Subscribe to inventory slot changes
if (_inventory != null)
{
_inventory.OnSlotChanged += HandleSlotChanged;
// Initialize with current slot
UpdateEquippedModel(_inventory.SelectedSlotIndex);
}
}
public override void OnNetworkDespawn()
{
// Unsubscribe to prevent memory leaks
if (_inventory != null)
{
_inventory.OnSlotChanged -= HandleSlotChanged;
}
// Clean up equipment
mainHandSlot?.Unequip();
}
private void HandleSlotChanged(int previousValue, int newValue)
{
UpdateEquippedModel(newValue);
}
private void UpdateEquippedModel(int slotIndex)
{
// Get item data for the selected slot
ItemData data = _inventory?.GetItemDataInSlot(slotIndex);
// Use new equipment slot system
if (data != null && data.CanBeEquipped)
{
// Use IEquippableItem interface
mainHandSlot.Equip(data);
}
else
{
mainHandSlot.Unequip();
}
// Update legacy reference for any code that might check it
_currentToolInstance = mainHandSlot.CurrentEquipment;
}
/// <summary>
/// Get the currently equipped item data.
/// </summary>
public ItemData GetEquippedItem()
{
return mainHandSlot?.EquippedItem;
}
/// <summary>
/// Get the currently equipped tool instance.
/// </summary>
public GameObject GetCurrentToolInstance()
{
return mainHandSlot?.CurrentEquipment ?? _currentToolInstance;
}
/// <summary>
/// Check if player has equipment in main hand.
/// </summary>
public bool HasMainHandEquipment => mainHandSlot?.HasEquipment ?? false;
/// <summary>
/// Force refresh the equipped model.
/// </summary>
public void RefreshEquipment()
{
if (_inventory != null)
{
UpdateEquippedModel(_inventory.SelectedSlotIndex);
}
}
/// <summary>
/// Get the main hand equipment slot for advanced usage.
/// </summary>
public EquipmentSlot MainHandSlot => mainHandSlot;
}