using Godot; using Godot.Collections; using System; using System.Linq; public partial class InventorySlot : Panel { [Export] public TextureRect IconRect; [Export] public Label CountLabel; public InventorySlotData SlotData; public int SlotIndex; public Inventory Inventory; // Refresh the current slot with the data of it's inventory slot public void Refresh() { if (SlotIndex < Inventory.Slots.Count()) { SlotData = Inventory.Slots[SlotIndex]; } if (SlotData == null) { IconRect.Texture = null; CountLabel.Text = ""; } else { IconRect.Texture = SlotData.Item.Icon; CountLabel.Text = (SlotData.Count > 1) ? SlotData.Count.ToString() : ""; } } // Handle Item being dragged elsewhere public override Variant _GetDragData(Vector2 atPosition) { if (SlotData == null) return default; // Create a preview of the item being dragged var preview = new TextureRect { Texture = SlotData.Item.Icon, CustomMinimumSize = new Vector2(32f, 32f) }; SetDragPreview(preview); var data = new Dictionary { { "from_slot", SlotIndex } }; return data; } // Can we drop the item where we are? public override bool _CanDropData(Vector2 atPosition, Variant data) { return data.VariantType == Variant.Type.Dictionary && ((Dictionary)data).ContainsKey("from_slot"); } public override void _DropData(Vector2 atPosition, Variant data) { int fromIndex = (int)((Dictionary)data)["from_slot"]; // Swap the 2 indexes (Inventory.Slots[SlotIndex], Inventory.Slots[fromIndex]) = (Inventory.Slots[fromIndex], Inventory.Slots[SlotIndex]); // Call the refresh method for all objects that belong in the inventory_slots group GetTree().CallGroup("inventory_slots_cs", InventorySlot.MethodName.Refresh); } public void InitializeSlot(int slotIndex, Inventory inventory) { SlotIndex = slotIndex; Inventory = inventory; Refresh(); } }