GetGuiObjectsAtPosition() function not working correctly?

For context, I currently have an inventory system setup so that each slot corresponds to a number, for example, Slot 1 should be at the top left corner of the inventory, while Slot 25 (the last slot) should be at the bottom right corner.

However, when I try to get the Slot that the player’s mouse is currently hovering over, I usually either get the completely wrong slot or no slot at all.

Gif:
https://gyazo.com/8093dd1333166fbbfa663556cfe190ba

Code:

local function HoverEnter(X, Y)
	local GuisAtPosition = PlayerGui:GetGuiObjectsAtPosition(X, Y)
	for _, GuiObject in ipairs(GuisAtPosition) do
		if GuiObject:IsA("ImageButton") then
			print("GuiObject located on slot: ", GuiObject.Name, " is a ImageButton")
		else
			print("GuiObject is not a ImageButton")
		end
	end
end

for _, InventorySlot in ipairs(TaggedInventorySlots) do --CollectionService
	if InventorySlot:IsA("ImageButton") then
		InventorySlot.MouseEnter:Connect(HoverEnter)
	end
end

Hierarchy:

I think it’s because it is also applying the GuiInset, which is 36 pixels taht are reserved for Roblox’s topbar, Try subtracting 36 from Y

local GuisAtPosition = PlayerGui:GetGuiObjectsAtPosition(X, Y - 36)

You may also have to apply it to the X as well if you’re still getting slight issues

6 Likes

Oh my god that worked perfectly, thank you so much!

1 Like

Sorry that I am bumping this old thread but for anybody that comes across this issue in the future, to futureproof your code use this function from GuiService:

local GuiInset = game:GetService("GuiService"):GetGuiInset()
local GuisAtPosition = PlayerGui:GetGuiObjectsAtPosition(X, Y - GuiInset.Y)
8 Likes