Detecting newly added buttons inside a script?

There is a weapon inventory, and naturally, the buttons for weapons are added after the player’s data is loaded/a new weapon is picked up. Currently, I can’t think of any way to detect these buttons inside the gui script. I need to make it so that when the player clicks on any of them, another GUI will be opened (and some properties of this GUI will change depending on the name of the button). So, how can I detect the buttons in a script?

I tried to detect the buttons when the player opens the inventory, but then the button click function gets stacked as the player opens/closes the inventory. When you open it for the first time and click on a button, the it prints only once. But once you close and then open the inventory, it prints three times. I played a bit with conn:Disconnect() to fix the issue but no luck, I can’t really think of any solution. Thanks in advance.

invButton.MouseButton1Click:Connect(function()
	inventoryFrame.Visible = not inventoryFrame.Visible
	
	local conn
	for i, v in pairs(script.Parent.weaponInventory:GetChildren()) do
		if v:IsA("TextButton") then
			conn = v.MouseButton1Click:Connect(function()
				print("e")
			end)
		end
	end
	
end)```

I would just say tween the gui out and make it invisible and then tween the other one in and make it visible.
And to detect newly added buttons in a script you could just do WaitForChild and check if it’s visible or not.

1 Like
local function onButtonAdded(button: GuiButton)
    -- Do stuff
end
for _, buttons in Buttons:GetChildren() do
    onButtonAdded(button)
end

Buttons.ChildAdded:Connect(onButtonAdded)

For the second problem, just define the connection outside of the function and at the beginning of the function, check if there is already a connection and disconnect it if there is.

Example:

local connection = nil

local button = script.Parent.TextButton

button.Activated:Connect(function()
	if connection then
		connection:Disconnect()
	end
	
	inventoryFrame.Visible = not inventoryFrame.Visible
	
	for i, v in pairs(script.Parent.weaponInventory:GetChildren()) do
		if v:IsA("TextButton") then
			connection = v.MouseButton1Click:Connect(function()
				print("e")
			end)
		end
	end
end)

It doesn’t work. I think the reason is that only one connection is stored/disconnected since there is only 1 connection variable. When there is more than one button, only the last button gets properly disconnected and prints 1 result as intended. The rest keeps getting stacked.

For anyone having a similar issue, all you have to do is detecting the newly created buttons in the script that creates them.

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