Input ended for mousebutton1 doesnt fire if mouse moves over a gui or off the screen

Hello, I have a script for a pickaxe and am having a lot of trouble making it work with the mouse button being held down. While the mouse button is held my script does a loop that fires a remote event checking if an ore was clicked. However i have a problem, if you hold down the mouse then move the mouse over a gui button or off the screen you can let go of the mouse button and the game doesnt fire the input ended function to stop the loop. If you keep repeating this the loops just keep starting and its a disaster. Here is the script

local ticket = 0 
local isHolding = false 

function leftMouseButtonHeld()
	isHolding = true	
	while isHolding == true do
		wait(0.05)
		print("Swinging")
		if player.PickaxeCooldown.Value == false then
			if Mouse.Target and string.match(Mouse.Target.Parent.Name, "Node") then						
				SwingEvent:FireServer(Mouse.Target.Parent)
			end
		end
	end
end


function leftMouseButtonReleased()
	if not isHolding then return end
	isHolding = false
	print("LMB released")
end

UserInputService.InputBegan:Connect(function(input, gameProcessed)
	if gameProcessed then return end

	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		ticket = ticket + 1 
		local currentTicket = ticket 
		
		if ticket == currentTicket then			
			leftMouseButtonHeld()
		end
	end
end)

UserInputService.InputEnded:Connect(function(input, gameProcessed)
	if gameProcessed then return end

	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		ticket = ticket + 1		
		leftMouseButtonReleased()
	end
end)

IIRC gameProcessed will be true if the mouse is over a GUI object so try removing that check.

thanks that worked for the guis i got this code from another post and didnt understand gameProcessed. However im still not sure how to make the loop stop if the players mouse exits the window while they are holding it down.

Do you mean when they lose focus of the window? I’m not sure if there is a way to listen for a specific key is released, that’d probably be a security flaw, allowing inputs to be recorded when Roblox isn’t focused. You can probably listen for userInputService.WindowFocusReleased and check isHolding, if isHolding is true then set it to false (or just connect WindowFocusReleased to leftMouseButtonReleased).

userInputService.WindowFocusReleased:Connect(leftMouseButtonReleased)

yea that makes sense i guess its not really an issue . The WindowFocusReleased helps thanks

1 Like