Sorting system for slots

--[[ Slots ]]

local TOWER_MODEL_PATH = ReplicatedStorage.Towers.ShopTowers
local TOWER_SLOT = script:WaitForChild("TowerSlot")
local MAX_TOWER_SLOTS = 6
local BUTTON_NUMBER = 1 --// Initialize the button number to 1
local existingTowers = {} --// Keep track of existing towers

for i = 1, MAX_TOWER_SLOTS do --// Cloning the slots
	local newTowerSlot = script.TowerSlot:Clone()
	newTowerSlot.Parent = gui.TowerSlots
	newTowerSlot.Number.Text = BUTTON_NUMBER --// Set the button text to the button number
	newTowerSlot.Name = "TowerSlot_" .. BUTTON_NUMBER

	--// Add viewport model
	for i, tower in pairs(towers) do
		for _, selectedTower in pairs(playerData.SelectedTowers) do
			if not selectedTower then return end

			-- Check if tower already exists
			if not existingTowers[selectedTower] and newTowerSlot.ViewportFrame then
				-- Check if viewport is already occupied
				local viewport = newTowerSlot.ViewportFrame
				existingTowers[selectedTower] = true -- Add tower to existing towers

				local Camera = Instance.new("Camera", viewport)
				local World = Instance.new("WorldModel", viewport)
				viewport.CurrentCamera = Camera
				local TowerModel = ReplicatedStorage.Towers.ShopTowers:FindFirstChild(selectedTower):Clone()
				Camera.CFrame = CFrame.new(-0.3, 0.5, 2)
				TowerModel.PrimaryPart.CFrame = CFrame.Angles(0, math.rad(145), 0)
				TowerModel.Parent = World
				-- print(TowerModel.Parent.." - Path | Name -  "..TowerModel.Name)
                --[[
                local Anim = TowerModel:WaitForChild("Animations")
                local Idle = Anim:WaitForChild("Idle")
                local animationTrack = TowerModel.Humanoid:LoadAnimation(Idle)
                animationTrack:Play()
                ]]
			end
		end
	end

	newTowerSlot.MouseButton1Click:Connect(function()
		for i, v in pairs(newTowerSlot.ViewportFrame:GetChildren()) do
			if v:IsA("Model") and i > 2 then
				v.Parent = nil
			end
		end
	end)

	BUTTON_NUMBER = BUTTON_NUMBER + 1
end

here in this script, I want to do like if the first slot it’s occupied it’ll go on to the next one. if all are occupied then it’ll print/warn smth.

You just need a function to loop over each possible slot and return the first one that’s available. If the function reaches the end it should warn. It could look something like this, but I don’t know how you’ve decided to identify occupied slots:

function nextTower()
	for slotIndex, towerSlot in pairs(towerSlots) do
		if towerSlot.Occupied == false then
			return slotIndex
		end
	end

	warn("No available tower slots")
	return nil
end
1 Like

uhm, how can I use it? it doesn’t work…

What do you mean? What did you write?

No, i mean how does it work. I mean do I parent the world model to the index? edit: alr I am dumb, so I not to the proper index, anyway I have figured out:d