MouseButton function on new Textbuttons

So basiclly I’m making a game where you harvest crops and you can sell them by clicking on one of the four gui characters, these are cloned from an example gui. For example a Golden gui frame has been cloned with as character cletus and a random amount of 48 raspberrys. But this isn’t my problem, my problem or struggle is you have to click this gui in order to sell it but it’s a gui created (cloned) while the game is running so I can’t predefine my mousebutton1Down functions on guis that doesn’t exist yet. But I can make a function that checks for new guis like the following:

local Player = game:GetService("Players").LocalPlayer
local TaskFolder = Player.PlayerGui.ScreenGui.TaskFrame.TaskFolder
local function SearchNewTasks()
 for _, task in pairs(TaskFolder:GetChildren()) do
  if task:IsA("Frame") then
   Frame.TextButton.MouseButton1Down:Connect(function()
    Print("Sold") --this is just an example
   end)
  end
 end
end

But then there is a new problem, once a task is completed the gui (clone) gets destroyed because the task is complete i don’t need it anymore, so there is now a spot for a new task. New gui meens I would have to run that function to check for new guis again and this would over time result in once a task is completed and sold (clicked) it would activate the MouseButton1Down function multiple times for the same task.

My solution so far, I would create a sepperate script to check for new guis and every time a task is completed and the script needs to check for new tasks, I would Disable and Enable the script again so the MouseButton1Down functions doesn’t stack over time.

Is there an easier way on how I can achieve my goal without creating a sepperate script?

When you create a new button, you can immediately connect a function to it in the same script:

local button = buttonTemplate:Clone()
button.MouseButton1Click:Connect(function()
    --whatever you want to happen
end)

No need for a separate script or anything. When this button gets destroyed, the connection will not work anymore, and you can create a new button with a new connected function.

1 Like

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