Is there any way I can know what GUI a player is hovering his mouse at?
Basically, I’m trying to make an inventory system, and right now I’m trying to make it so you can switch item slots.
You could use MouseEnter
event that comes with all GUI objects (More Info).
The above method is the easiest, but can be unreliable if the mouse moves too quickly.
An alternative method is game.Players.LocalPlayer:GetMouse()
, which returns the player mouse object. You can then get the .X and .Y of the mouse. Using .Button1Down
you can detect when the user presses their mouse down. With the above, you now know where the user is pressing. To move items, simply check if the mouse if over a object using .AbsolutePosition
and .AbsoluteSize
. For example:
local m = game.Players.LocalPlayer:GetMouse()
local function isHoveringOverObj(obj)
local tx = obj.AbsolutePosition.X
local ty = obj.AbsolutePosition.Y
local bx = tx + obj.AbsoluteSize.X
local by = ty + obj.AbsoluteSize.Y
if m.X >= tx and m.Y >= ty and m.X <= bx and m.Y <= by then
return true
end
end
local object = --Object to check
m.Button1Down:Connect(function()
if isHoveringOverObj(object) then
print('Object Pressed')
end
end)
Now, with a little modification, you can make this into a inventory system. (I have in the past)
Edit (10/31): Corrected typo
You could use the MouseEnter event on every GUI object.
local currentGui
guiObject.MouseEnter:Connect(function()
currentGui = guiObject
end)
guiObject2.MouseEnter:Connect(function()
currentGui = guiObject2
end)
--etc.
Use :GetGuiObjectsAtPosition()
I don’t need an answer anymore, but thanks for helping. I used something different for swapping slots in the inventory, and it’s working fine.
There are probably multiple ways to do this but when I was making a drag and drop inventory I used something like this:
local guisAtPosition = player.PlayerGui:GetGuiObjectsAtPosition(mouse.X, mouse.Y)
for _, gui in pairs(guisAtPosition) do
if gui:isA(“Frame”)
end
end
This is probably the easiest way to do this, I don’t know if there are other ways to see what gui you are hovering over besides this without checking every single button you want to be check with mouse.Enter.