I’m trying to spawn a Locker model only once each time this function runs. I’m trying to make a room spawning system like Doors. But it keeps spawning more than one, or none at all for some reason.
I wanted it so when the requiresLocker Parameter is true, then it spawns lockers based on the LockerCount parameter, but only spawns other furniture types when requiresLocker is false.
Code:
function furniture.FurnishRoom(room, requiresLocker, lockerCount)
local FurnitureTemplates = room:FindFirstChild("Furniture")
if not FurnitureTemplates then
return
end
local lockersSpawned = 0 -- To track how many lockers have been spawned
local totalTemplates = #FurnitureTemplates:GetChildren() -- Get the total number of furniture templates
-- Ensure that lockerCount doesn't exceed the number of templates available
lockerCount = math.min(lockerCount, totalTemplates)
for i, template in pairs(FurnitureTemplates:GetChildren()) do
local newFurniture = nil
if requiresLocker and lockersSpawned < lockerCount then
newFurniture = workspace.Furniture:WaitForChild("Locker"):Clone()
lockersSpawned = lockersSpawned + 1
else
-- Spawn random furniture if no more lockers need to be spawned
local randomIndex = furniture.Random:NextInteger(1, #furniture.TotalFurniture)
local selectedModel = furniture.TotalFurniture[randomIndex]:Clone()
newFurniture = selectedModel
end
-- If newFurniture is valid, set its position and parent it
if newFurniture then
-- Ensure that newFurniture has a primary part (it must to use SetPrimaryPartCFrame)
if newFurniture.PrimaryPart then
newFurniture:SetPrimaryPartCFrame(template.CFrame)
newFurniture.Parent = template.Parent
template:Destroy() -- Destroy the template once the furniture is placed
end
end
end
end