There are three problems with the example code at the BasePlayerGui/GetGuiObjectsAtPosition code example.
- The code example uses
pairs
in place ofipairs
for array-like loops (When usingGetChildren
) - The code example checks against GUIs that inheritt
GuiButton
, notGuiObject
as the documentation suggests. - The code example uses
Remove
instead ofDestroy
To fix these issues, I propose the following changes to the code example:
local UserInputService = game:GetService("UserInputService")
-- Get the LocalPlayer’s PlayerGui folder
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local PlayerGui = player:WaitForChild("PlayerGui")
-- Create a Folder and ScreenGui to contain the highlight Frames
local Highlights = Instance.new("Folder")
Highlights.Name = "Highlights"
Highlights.Parent = PlayerGui
local HighlightsContainer = Instance.new("ScreenGui")
HighlightsContainer.Name = "Container"
HighlightsContainer.Parent = Highlights
HighlightsContainer.DisplayOrder = 99999
-- Deletes all GUIs in HighlightsContainer
local function deleteHighlights()
local highlights = HighlightsContainer:GetChildren()
- for _, highlight in pairs(highlights) do
+ for _, highlight in ipairs(highlights) do
- highlight:Remove()
+ highlight:Destroy()
end
end
-- Creates a semi-transparent yellow Frame on top of the gui with the same AbsoluteSize and AbsolutePosition
local function highlightAsFrame(gui)
local highlight = Instance.new("Frame")
highlight.Name = "Highlight"
highlight.Parent = HighlightsContainer
highlight.Size = UDim2.new(0, gui.AbsoluteSize.X, 0, gui.AbsoluteSize.Y)
highlight.Position = UDim2.new(0, gui.AbsolutePosition.X, 0, gui.AbsolutePosition.Y)
highlight.BackgroundColor3 = Color3.new(255/255, 255/255, 10/255) -- Yellow
highlight.BackgroundTransparency = 0.75
highlight.BorderSizePixel = 0
highlight.LayoutOrder = gui.LayoutOrder -1
end
-- Use GetGuiObjectsAtPosition to get and highlight all GuiObjects at the input’s position
local function highlightGui(input, gameProcessed)
local pos = input.Position
local guisAtPosition = PlayerGui:GetGuiObjectsAtPosition(pos.X, pos.Y)
deleteHighlights()
- for _, gui in pairs(guisAtPosition) do
+ for _, gui in ipairs(guisAtPosition) do
- if gui:IsA("GuiButton") then
+ if gui:IsA("GuiObject") then
local highlight = gui:Clone()
highlightAsFrame(gui)
end
end
end
-- Fire highlightGui on InputBegan if input is of type MouseButton1 of Touch
local function InputBegan(input, gameProcessed)
local inputType = input.UserInputType
local touch = Enum.UserInputType.Touch
local mouse1 = Enum.UserInputType.MouseButton1
if inputType == touch or inputType == mouse1 then
highlightGui(input, gameProcessed)
end
end
UserInputService.InputBegan:Connect(InputBegan)
Note: I had to add a space at the start of each comment line, otherwise diff will mark it as line removed.