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?
How to detect if player's mouse is over a button?
2 answers
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.
local Player = game:GetService("Players").LocalPlayer
local PlayerGui = Player:WaitForChild("PlayerGui")
local Cursor = Player:GetMouse()
local function ChangeCursorOverGui()
local X,Y = Cursor.X, Cursor.Y
local GuiObjects = PlayerGui:GetGuiObjectsAtPosition(X,Y)
for _,Button in pairs(GuiObjects) do
if (Button:IsA("GuiButton")) then
--// Change Cursor
return end
end
--// Reset Cursor
end
Cursor.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!
3 comments
I have a tween for the button for entering and exiting but the exiting tween won't play.
Never mind, I've fixed it. Thank you for this god tier script.
No problem!
Hello. You can use the MouseEnter event. Try this: (Assuming that the LocalScript is inside the button)
script.Parent.MouseEnter:Connect(function()
script.Parent.BackgroundColor3 = Color3.fromRGB(R, G, B)
end)
You may change "R, G, B" to the color of your choice. Please accept and upvote this answer if it helped.
1 comment
I said "It seems excessive to put a script in every button."
This discussion is preserved as it was. New answers, comments, and votes are closed.

2 comments
My answer is the most efficient, the other answers will run it too many times causing memory problems.
That's false. In fact, it's the least efficient after reading it.