Make gamepad cursor work with selecting

  1. What do you want to achieve? Keep it simple and clear! I want to make a cursor for gamepad users which is a quality of life feature.

  2. What is the issue? Include screenshots / videos if possible! The issue is when the cursor image label is hovering over gui, it only selects the Test2 text button as seen in the video: issue video no.1 - YouTube

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub? I look for detecting guis and it lead to me having a somewhat working detection script.

Code:

--Xbox stuff

local CursorEnabled = false --The crosshair cursor thing you see

local UserInputService = game:GetService("UserInputService")
local GuiService = game:GetService("GuiService")

UserInputService.InputBegan:Connect(function(key)
	if UserInputService.GamepadEnabled then
		if key.KeyCode == Enum.KeyCode.ButtonX then
			CursorEnabled = not CursorEnabled
			print(CursorEnabled)
		end
	end
end)

UserInputService.InputChanged:Connect(function(key)
	if UserInputService.GamepadEnabled then
		if CursorEnabled and key.KeyCode == Enum.KeyCode.Thumbstick1 then
			script.Parent.Cursor.Position += UDim2.new(0, key.Position.X * 5, 0, -key.Position.Y * 5)
			
			task.spawn(function()
				for index, ui in pairs(script.Parent:GetDescendants()) do
					if ui:IsA("GuiObject") and ui ~= script.Parent.Cursor then
						if math.abs(ui.Position.X.Offset - script.Parent.Cursor.Position.X.Offset) < 5 then
							GuiService.SelectedObject = ui
						elseif math.abs(ui.Position.Y.Offset - script.Parent.Cursor.Position.Y.Offset) < 5 then
							GuiService.SelectedObject = ui
						else
							GuiService.SelectedObject = nil
						end
						print(GuiService.SelectedObject)
					end
				end
			end)
		end
	end
end)