How to detect if the player is holding on the button

Hi, there.
I am trying to continue printing (“.”) in the output while the player click and holds a GUI button. And when they stop I want it to stop printing (“.”)

Local script in a ui button

local Button = script.Parent

local Clicked = false

Button.MouseButton1Down:Connect(function(plr)
	Clicked = true

	game.ReplicatedStorage.folder.Eventa:FireServer(plr)
	while Clicked do
		wait(.2)
	end
	game.ReplicatedStorage.folder.Eventb:FireServer(plr)
end)

Button.MouseButton1Up:Connect(function(plr)
	Clicked = false
end)

Script in serverscriptservice

game.ReplicatedStorage.folder.Eventa.OnServerEvent:Connect(function(plr)
	local a = true
	while a == true do
		task.wait(1)
		print(".")
	end
	game.ReplicatedStorage.folder.Eventb.OnServerEvent:Connect(function(plr)
		a = false
	end)
end)

Issue I am running into is when the player only clicks the button it continues printing (“.”) and doesn’t stop.

The while loop will yield, causing the OnServerEvent of Eventb to not run. Move that ahead of the while loop and it will stop the print

I also recommend changing this to :Once to prevent memory leaks

2 Likes

Thanks for your reply!
I tried doing this:

Now it won’t print(“.”) at all

a is false so it doesn’t print lol. Anyways this is not going to work, I mean placing it ahead like this:

game.ReplicatedStorage.folder.Eventa.OnServerEvent:Connect(function(plr)
	local a = true
	game.ReplicatedStorage.folder.Eventb.OnServerEvent:Once(function(plr)
		a = false
	end)
	while a == true do
		task.wait(1)
		print(".")
	end
end)
1 Like

Thanks for your help!!

this text is

1 Like

Not sure if you fixed this or not … this sure looks odd.
The logic in your local script is a bit off and I’m not sure why you’re firing a remote here.
Here is a very simple local script that will do what you want …
If you’re really doing something else here the is a good base.

local Button = script.Parent
local Clicked = false

local function PrintDots()
	while Clicked do
		print(".")
		task.wait(0.33)
	end
end

Button.MouseButton1Down:Connect(function()
	Clicked = true
	PrintDots()
end)

Button.MouseButton1Up:Connect(function()
	Clicked = false
end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.