Function running several times when only clicked once

  1. What do you want to achieve?

When the user clicks a button with a “type” attribute, the game will then take it and use that type to do stuff.

-- Manage View / Spawn Buttons --
pageLayout.CurrentPage.Changed:Connect(function()
	for _,item in pageLayout.CurrentPage:GetDescendants() do
		if item.ClassName == "TextButton" then
			if item:GetAttribute("Type") ~= nil then
				item.MouseButton1Click:Connect(function()
					if item:GetAttribute("Type") == "View" then
						warn("VIEW")
					elseif item:GetAttribute("Type") == "Spawn" then
						warn("SPAWN")
					else
						warn(script.Name.. ": Button Type Not Recognized For " ..plr.Name)
					end
				end)
			end
		end
	end
end)
  1. What is the issue?

When I press the button, the code runs many times despite only being clicked once.
image

  1. What solutions have you tried so far?

After looking on the dev forum for a bit, I found two posts here and here.
I tried the method on post #2, but it ended up breaking more stuff causing it to just not recognize some of the buttons for some reason. I would try post #1, but disconnecting and stuff confuses me and has never been an issue any other time I’ve used it.

2 Likes

I’m pretty sure not disconnecting it IS the problem (or debounce issue).

Try:

-- Manage View / Spawn Buttons --
local connections = {}

pageLayout.CurrentPage.Changed:Connect(function()
	for _, connection in connections do
		connection:Disconnect()
	end
	
	for _,item in pageLayout.CurrentPage:GetDescendants() do
		if item.ClassName == "TextButton" and item:GetAttribute("Type") ~= nil then
			local connection = item.MouseButton1Click:Connect(function()
				if item:GetAttribute("Type") == "View" then
					warn("VIEW")
				elseif item:GetAttribute("Type") == "Spawn" then
					warn("SPAWN")
				else
					warn(script.Name.. ": Button Type Not Recognized For " ..plr.Name)
				end
			end)
			
			table.insert(connections, connection)
		end
	end
end)

My assumption is that there are previous connections from other page changes which is why there are so many button clicks. If you store all the connections together you can easily disconnect them when you open a new page.

1 Like

It might also be important for me to mention that there are other onMouseClick events in the same script but those are connected to specific buttons.
Giving this a try though I’ll let you know how it goes.

1 Like

After a bit of messing around with it and adjusting for the rest of the script it worked perfectly. Thankyou!

Goes to show I should probably learn more about this stuff ._.

1 Like

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