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.
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.