I’m making a game that has a feature where spawners spawn a tool in a certain time but there is a problem in where it spawns at the same spot even though an object is already there
Current Script:
local timePeriod = 15
local despawnTime = 10
debris = game:GetService("Debris")
while true do
wait(timePeriod);
local spawns = script.Parent:GetChildren();
valid = false
while valid == false do
spawnPoint = spawns[math.random(1, #spawns)];
if spawnPoint.Name ~= "spawnscript" then
if spawnPoint.occupied.Value == false then
valid = true
end
end
end
local object = game.ServerStorage.SpawnItems.apol:Clone()
object.Parent = workspace
object.Handle.Position = spawnPoint.Position
debris:AddItem(object, despawnTime)
end
How do I make it so only 1 item spawns inside a random spawner only if there is nothing in that spawner.
You need to set spawnPoint.occupied.Value to true otherwise it’s going to be remain unoccupied. Do this after you set valid to true.
It also recommended you start variables with local instead of just assigning the variable name. This won’t have an effect on the functionality of your code though it is just better practice.
local timePeriod = 15
local despawnTime = 10
debris = game:GetService("Debris")
while true do
task.wait(timePeriod);
local spawns = script.Parent:GetChildren();
while true do
spawnPoint = spawns[math.random(#spawns)];
if spawnPoint:IsA("BasePart") and spawnPoint:FindFirstChild("occupied") and spawnPoint.occupied.Value == false then
spawnPoint.occupied.Value = true
break
end
task.wait() -- just in case all spots are occupied it won't timeout
end
local object = game.ServerStorage.SpawnItems.apol:Clone()
object.Handle.Position = spawnPoint.Position
object.Parent = workspace
debris:AddItem(object, despawnTime)
end
Did some other misc changes such as:
wait(timePeriod) → task.wait(timePeriod) (new task library)
spawns[math.random(#spawns)] instead of spawns[math.random(1, #spawns)]
The if statement for determining if the spawn is occupied or not
Parenting the object after setting it’s Position property (for performance reasons, see here)
Removed the valid variable and just broke the loop if the condition was met