sasalka/Code/Inventory/Inventar.cs
2025-06-26 01:56:08 +03:00

99 lines
2.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

namespace Sasalka;
public class Inventar
{
[Flags]
public enum InventorySlot
{
None = 0,
LeftHand = 1 << 0, // 1
RightHand = 1 << 1, // 2
Head = 1 << 2, // 4
Body = 1 << 3, // 8
Hands = 1 << 4, // 16
Bottom = 1 << 5, // 32
Feet = 1 << 6 // 64
}
public List<InventoryItem> Items { get; private set; } = new();
public static bool IsInventoryOpen = false;
public Dictionary<InventorySlot, InventoryItem> EquippedItems { get; private set; } = new();
public event Action OnChanged;
public event Action<InventoryItem> OnEquipped;
public event Action<InventoryItem> OnUnEquipped;
public void AddItem( InventoryItem item )
{
Items.Add( item );
OnChanged?.Invoke();
}
public void RemoveItem( InventoryItem item )
{
UnEquipItem( item );
Items.Remove( item );
OnChanged?.Invoke();
}
public void EquipItem( InventoryItem item )
{
if ( item.Definition is not IEquipable equipable )
return;
// Если уже экипирован этот же предмет — снять его
if ( EquippedItems.ContainsValue( item ) )
{
UnEquipItem( item );
return;
}
// Если на этом слоте уже что-то есть — снять старый предмет
if ( EquippedItems.TryGetValue( equipable.Slot, out var oldItem ) )
{
UnEquipItem( oldItem );
// Вернуть снятый предмет обратно в инвентарь, если его там нет
if ( !Items.Contains( oldItem ) )
Items.Add( oldItem );
}
// Экипировать новый предмет
EquippedItems[equipable.Slot] = item;
item.Equipped = true;
OnEquipped?.Invoke( item );
}
public void DropItem( InventoryItem item, Vector3 position )
{
GameObject gO = item.Definition.Prefab.Clone( position );
if ( gO.Components.TryGet<InventoryItem>( out var inventoryItem ) )
{
inventoryItem.Count = item.Count;
if ( inventoryItem.Definition == null )
{
inventoryItem.Definition = item.Definition;
}
}
gO.NetworkSpawn( null );
RemoveItem( item );
Items.Remove( item );
OnChanged?.Invoke();
}
public void UnEquipItem( InventoryItem item )
{
foreach ( var kvp in EquippedItems.Where( kvp => kvp.Value == item ).ToList() )
{
EquippedItems.Remove( kvp.Key );
}
item.Equipped = false;
OnUnEquipped?.Invoke( item );
}
}