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 4 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 — 4y
0
That's false. In fact, it's the least efficient after reading it. Ziffixture 6913 — 4y

2 answers

Log in to vote
1
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
4 years ago
Edited 4 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.

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!

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

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
I said "It seems excessive to put a script in every button." DejaSketch 84 — 4y

Answer this question