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

How do I make a loop end with a MouseButton1Click toggle?

So I have a while wait() do loop because thats the only way that can run this PlaybackLoudness code (I think), and I want to be able to have it so when you click it, it turns on that color and fades with the beat. But when you click it again, it just turns to black, how would I do that? Heres the code:

local music = game.Workspace.Sound

script.Parent.MouseButton1Click:Connect(function()
	local player = game.Players.LocalPlayer
	local bracelet = player.Character.Bracelet2
	while wait() do
		bracelet.Color = Color3.new(music.PlaybackLoudness/255, music.PlaybackLoudness/0, music.PlaybackLoudness/0)
	end
end)

1 answer

In a typical scenario you can use return to stop any loop or function that is active (alt "break") but in this case you will need a function inside of your existing function so we can just use a bit of logic to work around our issue.

Here is some sample code I threw together to help you fix your issue

local flag = true --Variable that is required to be true

while wait() do
	if(not flag)then --Make sure the flag is true, if not then return (AKA break the loop) 
		return;
	end
	
	print("hey! I did something! :D")--This code will run if left click has not been pressed. 
	
	local Player = game.Players.LocalPlayer --These are required for the click event
	local Mouse = Player:GetMouse()
	
	Mouse.Button1Down:connect(function()
		flag = false
		print("break this thang")
	end)
end

Also, you could really have the MouseDown function outside the main function (or in this case the while loop) buuutttt I didn't do that soo.. here ya go.

1 comment

0

Most of the time, you should not connect events in a loop. Also, break is for loops, not return.

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