How to make loops pass the wait

so here my code

wait(7)
while wait() do
	for i, v in pairs(game.Workspace.Area1DummySpawn:GetChildren()) do
		if v:IsA("BasePart") then

			if v:FindFirstChild("Used").Value == false then
				task.wait(5)
				v.Used.Value = false

				local dummy = game.Workspace.Area1Dummy:Clone()

				if v.Used.Value ~= true then
					dummy:SetPrimaryPartCFrame(v.CFrame)

					v.Used.Value = true
					dummy.Parent = v
				end
				v.Used.Value = true
			end

		end
	end
end

i want this script so that everytime the Used.Value = false the lines after that will happen but not affect the loop and make it stop. So like i have 2 blocks and i make the Used.Value = false on one and then make the Used.Value = false on the other one 2 seconds later, i want it so after 5 seconds the first one will make the Used.Value = true then after another 2 seconds the other one goes back to true. But whats happening is the second one wont go back till 5 seconds after the first one because it is pausing the script

1 Like

For this sort of thing, you can either use coroutines or task.spawn()
I personally find task.spawn() easier but you can do either.

Using task.spawn, it would look like this:

wait(7)
while wait() do
	for i, v in pairs(game.Workspace.Area1DummySpawn:GetChildren()) do
		task.spawn(function()
			if v:IsA("BasePart") then

				if v:FindFirstChild("Used").Value == false then
					task.wait(5)
					v.Used.Value = false
	
					local dummy = game.Workspace.Area1Dummy:Clone()

					if v.Used.Value ~= true then
						dummy:SetPrimaryPartCFrame(v.CFrame)

						v.Used.Value = true
						dummy.Parent = v
					end
					v.Used.Value = true
				end
			end
		end)
	end
    task.wait(1) -- You need to add some sort of the delay in the loop, otherwise it will timeout.
end

You can modify your script further to rely on connections, instead of a loop, to detect when the values change, which would make the code more efficient. If you want me to write up some code that does that, please let me know