So I have a custom Inventory and Hotbar, I want to know what I should use to detect when player hovers/clicks on a GUI. I know I could use invisible TextButtons but maybe there’s a better way
Here are my options so far:
- Have a
:MouseEnter
and :MouseLeave
Event for every GUI Frame
- Do
:GetGuiObjecstAtPosition
on Mouse.Move (might be more complicated to code)
Also if I have Events for non visible frames will they still be running, or does it automatically pause?
Basically I want to know what the least expensive way of checking if mouse position is over gui frame.
2 Likes
Try looping through all the GUI objects and connecting their MouseEnter
and MouseLeave
functions.
The least expensive way is probably using MouseEnter
and MouseLeave
Though, it can be pretty inaccurate. What you could do for a more accurate one, is make a ModuleScript and every time your mouse moves, the ModuleScript gets required.
Why a ModuleScript?
This is because if you’re gonna check if the mouse is hovering over more stuff with different scripts, it would take less to define it every time with a function IsHovering()
or something like that.
IF only one script would be using that, making a local function would be the best option.
Inside the ModuleScript you will need to check where the mouse is, and if it is inside the GUI, then return true
, not an entire function, that would be more expensive.
If true is returned then do the function.
Here’s an example for a ModuleScript:
local module = {}
local m = game.Players.LocalPlayer:GetMouse()
function module:Hover(obj) --where obj is the gui you're check if the player's mouse is over
local PosX = obj.AbsolutePosition.X
local PosY = obj.AbsolutePosition.Y
local SizeX = PosX + obj.AbsoluteSize.X
local SizeY = PosY + obj.AbsoluteSize.Y
if mouse.X >= PosX and mouse.Y >= PosY and mouse.X <= SizeX and mouse.Y <= SizeY then
return true --if the mouse is hovering over the gui, it returns true
end
end
return module
Okay thanks for the reply I will try it out.
Do you know if Events like Gui:MouseEnter
listen when a Gui is non visible, if they do wouldn’t that be a waste and I should probably manually disconnect them when the Gui is non visible?
MouseEnter does not work on invisible GUIs.
It is shown in the video below as well:
Though, for the code I provided, from the script where you’re gonna call the ModuleScript, you should add an if then
statement for checking if it’s visible or not. Since that code also returns true
for invisible GUIs.
1 Like