Connect a function only while mouse is in GUI

Hello Devforum!

I am learning basics of scripting and would like to know how to use the mouse.Move event ONLY while the mouse is hovering over a certain UI. Any solutions would be great, thanks!

local mouse = game.Players.LocalPlayer:GetMouse()
local inside = false

mouse.Move:Connect(function() -- doesn't run at first, but starts running once mouse enters UI
	game.Players.LocalPlayer.PlayerGui.UIitem.Frame.Position = UDim2.new(0,mouse.X,0,mouse.Y)
	wait()
end)

script.Parent.MouseEnter:Connect(function()
	inside = true
	-- mouse move function connects
end)

script.Parent.MouseLeave:Connect(function()
	inside = false
	-- mouse move function disconnects
end)

You would use an if check:

local mouse = game.Players.LocalPlayer:GetMouse()
local inside = false

mouse.Move:Connect(function() -- doesn't run at first, but starts running once mouse enters UI
    if inside then -- run if `inside` is `true`
	   game.Players.LocalPlayer.PlayerGui.UIitem.Frame.Position = UDim2.new(0,mouse.X,0,mouse.Y)
    end
end)

script.Parent.MouseEnter:Connect(function()
	inside = true
	-- mouse move function connects
end)

script.Parent.MouseLeave:Connect(function()
	inside = false
	-- mouse move function disconnects
end)

No, sorry if it wasn’t clarified, but I want the function to only connect while the mouse is hovering over a UI, otherwise the mouse.Move function will run indefinitely in the background.

In that case, you would want to store an RBXScriptConnection inside a variable in order to disconnect and connect it:

local mouse = game.Players.LocalPlayer:GetMouse()
local inside = false
local mouseConnection = nil -- holds the event connection

local function mouse_move()
	game.Players.LocalPlayer.PlayerGui.UIitem.Frame.Position = UDim2.new(0,mouse.X,0,mouse.Y)
end

script.Parent.MouseEnter:Connect(function()
	inside = true
    if not mouseConnection then -- check if a connection isn't already connected (prevents duplicate connections)
        mouseConnection = mouse.Move:Connect(mouse_move)
    end
end)

script.Parent.MouseLeave:Connect(function()
	inside = false

	if mouseConnection then -- check if the connection is binded first (to prevent errors)
       mouseConnection:Disconnect() -- disconnect the connection
       mouseConnection = nil -- clear the variable
    end
end)

Unless I misinterpreted again?

1 Like

Testing it right now, thanks for your time!

I added an extra line since I forgot to include it:

Just was about to point that out, but I got it and everything works great, thanks!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.