Hello! The code below swaps 2 item slots in my inventory system. It works perfectly! However, I feel like it’s very messy and I don’t know how to make it look better.
I have considered using tables, but I’m not sure how to use them in this case.
Thanks for any help ![]()
slot1 and slot2 are indexes within a SlotFrames table, which contains 50 slots. Some of them are empty, some have items.
Every slot frame which isn’t empty has an ItemModel and a ViewportCamera, which are used for the viewport of the item.
slotsWereSwapped.OnClientEvent:Connect(function(slot1, slot2)
local slotFrame1 = SlotFrames[slot1]
local slotFrame2 = SlotFrames[slot2]
local slotFrame1Info = slotFrame1:Clone()
local slotFrame2Info = slotFrame2:Clone()
slotFrame1.Name = slotFrame2Info.Name
slotFrame2.Name = slotFrame1Info.Name
slotFrame1.ItemViewport:ClearAllChildren()
slotFrame2.ItemViewport:ClearAllChildren()
slotFrame1.Amount.Text = slotFrame2Info.Amount.Text
slotFrame2.Amount.Text = slotFrame1Info.Amount.Text
for _, v in pairs(slotFrame1Info.ItemViewport:GetChildren()) do
if not slotFrame1.ItemViewport:FindFirstChild(v.Name) then
local clone = v:Clone()
clone.Parent = slotFrame2.ItemViewport
if clone:IsA("Camera") then
slotFrame2.ItemViewport.CurrentCamera = clone
end
end
end
for _, v in pairs(slotFrame2Info.ItemViewport:GetChildren()) do
if not slotFrame1.ItemViewport:FindFirstChild(v.Name) then
local clone = v:Clone()
clone.Parent = slotFrame1.ItemViewport
if clone:IsA("Camera") then
slotFrame1.ItemViewport.CurrentCamera = clone
end
end
end
end)