Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do i get a while loop to start and stop?

when OtherPart touches the MainPart the while loop stops, and if the OtherPart stops touching the while loop should start up again. but it does not please help!

local part = script.Parent

debounce = true
	
function onTouch(part)
    if debounce then
        if part.Parent:WaitForChild("Otherpart") then
	    print(part,"Touched")       
            debounce = false   ---------------  if touched then stops loop
        end
    end
end
	 
function onTouchEnded(part)
    if part.Parent:FindFirstChild("Otherpart") then
	print(part,"Touched Ended")
	debounce = true ------------------ if touch Ended then Restarts loop
    end
end

part.Touched:Connect(onTouch)
part.TouchEnded:Connect(onTouchEnded)

while debounce do   ----------------------------------- loop to start or stop
	wait()
	part.BrickColor = BrickColor.Random()
end

2 answers

✓ Accepted answer

The code is working exactly how you wrote it, here's why. On line 24, you put while debounce do. What this is saying is lines 25 and 26 will only run while debounce == true. The moment it's no longer true, the while loop is now finished, and any line after line 27 (where the loop ends) may now run. If you want it to loop over and over as you wish, you could do the following:

while true do
	if debounce then
		part.BrickColor = BrickColor.Random()
	end
	wait()
end

Note: This isn't the most efficient way of doing it, but for the sake of your learning process, this will meet your needs. If you're interested in efficiency, when you set the debounce to true, you could do a spawn() function to start the while loop manually each time.

1 comment

1

Your a GOD :) Bows Down

while wait(5) do
local part = script.Parent
debounce = true
function onTouch(part)
    if debounce then
        if part.Parent:WaitForChild("Humanoid") then
        print(part,"Touched")       
            if not debounce then debounce = false   ---------------  if touched then stops loop
        end
    end
end
end

function onTouchEnded(part)
    if part.Parent:FindFirstChild("Humanoid") then
    print(part,"Touched Ended")
    debounce = true ------------------ if touch Ended then Restarts loop
    end
end

part.Touched:Connect(onTouch)
part.TouchEnded:Connect(onTouchEnded)
while wait () do   ----------------------------------- loop to start or stop
    wait(1)
    part.BrickColor = BrickColor.Random()
debounce = false
end
end

This discussion is preserved as it was. New answers, comments, and votes are closed.