The loop that connects the event for the initial buttons can continue to be used, however, a ChildAdded
event can be used alongside this so that any new GuiButtons that are added into the “trunkButtons” and “inventoryButtons” activate the intended function/RemoteEvent.
In this case, we’ll create a new function so that the event connection can be created in a singular place (adhering by the “DRY”/Don’t Repeat Yourself principle) rather than duplicating the button.MouseButton1Click:Connect(function()
to each loop/function.
local function buttonEventConnection(button, buttonType)
if button:IsA("GuiButton") and buttonType == "trunk" then
button.MouseButton1Click:Connect(function()
moveToTrunkEvent:FireServer(button.toolItem.Value)
end)
elseif button:IsA("GuiButton") and buttonType == "inventory"
button.MouseButton1Click:Connect(function()
moveToInventoryEvent:FireServer(button.toolItem.Value)
end)
end
end
Afterwards, the loops can be modified to activate that function for each button so that the event can be connected:
for i, button in ipairs(trunkButtons) do
buttonEventConnection(button, "trunk")
end
for i, button in ipairs(inventoryButtons) do
buttonEventConnection(button, "inventory")
end
Then, the same thing can be applied for the new items that are added into the “trunkButtons” and “inventoryButtons”
trunkButtons.ChildAdded:Connect(function(item)
buttonEventConnection(item, "trunk")
end)
inventoryButtons.ChildAdded:Connect(function(item)
buttonEventConnection(item, "inventory")
end)
Afterward, here’s what everything looks like!
openGuiEvent.OnClientEvent:Connect(function(trunkItems, plrItems)
-- open gui --
frame.Visible = true
local frame = script.Parent
loadAllItems(plrItems, trunkItems)
--- New Code Below ---
local function buttonEventConnection(button, buttonType)
if button:IsA("GuiButton") and buttonType == "trunk" then
button.MouseButton1Click:Connect(function()
moveToTrunkEvent:FireServer(button.toolItem.Value)
end)
elseif button:IsA("GuiButton") and buttonType == "inventory"
button.MouseButton1Click:Connect(function()
moveToInventoryEvent:FireServer(button.toolItem.Value)
end)
end
end
for i, button in ipairs(trunkButtons) do
buttonEventConnection(button, "trunk")
end
for i, button in ipairs(inventoryButtons) do
buttonEventConnection(button, "inventory")
end
trunkButtons.ChildAdded:Connect(function(item)
buttonEventConnection(item, "trunk")
end)
inventoryButtons.ChildAdded:Connect(function(item)
buttonEventConnection(item, "inventory")
end)
end)