Efficient way to check smt

I have a script that randomly [that’s a lie, but I don’t necessarily know how often] duplicates a frame that has a button in it.
I would like to check efficiently in a script whether the mouse is over a button. What is the most efficient and easiest way to do this?
And how do I check whether a button has been pressed? And which one was it?
Thank you for your help.

Use GuiObject#MouseEnter and GuiObject#MouseLeave to detect when the mouse hovers over your button. You can also use GuiButton#MouseButton1Click to detect when the mouse clicks your button.

local button = path.to.the.button

button.MouseEnter:Connect(function() 
-- this code will run whenever the mouse hovers over the button
end)

button.MouseLeave:Connect(function()
-- this code will run whenever the mouse stops hovering over the button if you need it
end)

button.MouseButton1Click:Connect(function()
-- this code will run when the user clicks on the button
end)

I create sometimes like 100 buttons. I will not write this for every button. I mean I don’t even know if there are 5 or 10 buttons.

you are cloning the frames, its already going to be there.

I actually want to avoid exactly that. Isn’t that super inefficient? I’d prefer a single script.

you are cloning the frames, if you just put one script in the one frame you are cloning, then in-game it will already clone the script

I would say that it is very inefficient to have 50 scripts for 50 Buttons that all check if the mouse is over them. This is not only inefficient but also ugly. Is there any other good way?

in the script you are using to clone the frames, you can make a function meant for cloning. inside that function, you can detect inside the frame when mouseenter or leave.

You don’t need to rewrite the code for every script. I cannot provide an exact copy-and-paste script because I am not aware of your project’s structure, but if you clone the frame and then connect the events to each button of the newly cloned frame while still in the cloning loop/algorithm, you only need to write it once. Essentially, put the button action logic in the same scope as the cloning logic.

Use collection Service to group the buttons you want to work with

1 Like
local newFrame = frame:Clone()
newFrame.Button.MouseButton1Click:Connect(function()
   --as you can see, you only really write it once without multiple scripts
end)

1 Like

Oups, last night at 11pm I was too stupid to understand what you meant, thanks, it works!

1 Like

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