How would I create a button with code and assign an event to it?

Edit: so I figured it out.

I basically run a function that creates a bunch of buttons. And then for each button it attaches an event. Looks like this:

And it works. But everytime I run the 'recalibrateParties()` I will end up destroying all the buttons. How do I null the event connections? Cause otherwise I think that’s not very efficient, since in theory they will just keep stacking up to null buttons.

Or when you destroy the button in this case, does it disconnect the function?

function onJoin(frame) 
	print(frame.Name)
end


function recalibrateParties()
	local partyCountTotal = workspace:WaitForChild("PartyData"):WaitForChild("PartyCountTotal").Value
	local partyList = main:WaitForChild("PartyList"):WaitForChild("ScrollingFrame")
	local partyTemplate = partyList:WaitForChild("PartyTemplate")
	partyList.Visible = true
	backButton.Visible = true
	partyList.CanvasSize = UDim2.new(0, 0, partyCountTotal*2, 0)
	for i = 1,partyCountTotal do
		local newParty = partyTemplate:Clone()
		newParty.Parent = partyList
		newParty.Position = newParty.Position + UDim2.new(0, 0, 0, (partyCountTotal*200))
		newParty.Visible = true
		newParty.Name = "Party#"..tostring(partyCountTotal)
		newParty:WaitForChild("JoinButton").MouseButton1Down:Connect(onJoin(newParty))
			print(newParty.Name)
	end
	end

the connections get disconnected if the instance is destroyed. But if you want to be super safe., you can make a connection table like so

connection = {}

connection[i] = newParty:WaitForChild("JoinButton").MouseButton1Down:Connect(onJoin(newParty))
			print(newParty.Name)
end

to disconnect them, loop through the connection variable and call disconnect
1 Like

Connecting a function with arguments like this won’t work as expected since it calls the function and the event is connected to whatever the function returns

Instead you would need to connect it to a new function that calls the onJoin function with the arguments

.MouseButton1Down:Connect(function()
	onJoin(newParty)
end)
1 Like

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