Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

How to detect if player's mouse is over a button?

Asked by 5 years ago

I have a custom mouse in my game, without using the mouse.Icon, and I want the mouse color to change when the player hovers over a button, but it seems excessive to put a script in every button. What's an efficient way to do this?

0
My answer is the most efficient, the other answers will run it too many times causing memory problems. recanman 88 — 5y
0
That's false. In fact, it's the least efficient after reading it. Ziffixture 6913 — 5y

2 answers

Log in to vote
1
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
5 years ago
Edited 5 years ago

You can use the :GetGuiObjectsAtPosition() method of PlayerGui. If we apply this in conjunction with the .Move signal of Mouse, we can perpetually track the X & Y position of the Cursor on-screen. By feeding these two properties into our method of PlayerGui, we can find what GuiObjects the Cursor is currently hovering over.

Since :GetGuiObjectsAtPosition() returns an array, we use a pairs loop to iterate through each Instance. and filter for a GuiButton.

01local Player = game:GetService("Players").LocalPlayer
02 
03local PlayerGui = Player:WaitForChild("PlayerGui")
04local Cursor = Player:GetMouse()
05 
06local function ChangeCursorOverGui()
07    local X,Y = Cursor.X, Cursor.Y
08    local GuiObjects = PlayerGui:GetGuiObjectsAtPosition(X,Y)
09    for _,Button in pairs(GuiObjects) do
10        if (Button:IsA("GuiButton")) then
11            --// Change Cursor
12        return end
13    end
14    --// Reset Cursor
15end
16 
17Cursor.Move:Connect(ChangeCursorOverGui)

Use this code within a LocalScript under StarterGui for appropriate placement. Some debouncing such as an IsAlreadyHovering boolean would increase efficiency, though isn't much of an issue to worry about.

I have tested this in Studio, and it works marvelously!

If this helped, don't forget to accept this answer!

0
I have a tween for the button for entering and exiting but the exiting tween won't play. DejaSketch 84 — 5y
1
Never mind, I've fixed it. Thank you for this god tier script. DejaSketch 84 — 5y
0
No problem! Ziffixture 6913 — 5y
Ad
Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

Hello. You can use the MouseEnter event. Try this: (Assuming that the LocalScript is inside the button)

1script.Parent.MouseEnter:Connect(function()
2    script.Parent.BackgroundColor3 = Color3.fromRGB(R, G, B)
3end)

You may change "R, G, B" to the color of your choice. Please accept and upvote this answer if it helped.

1
I said "It seems excessive to put a script in every button." DejaSketch 84 — 5y

Answer this question