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)
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)