How can I detect if someone is holding a mouse button

So Im trying to make a script which detects if a mouse button is being held if it is then it’ll print(“Not Held”) If it is then it’ll print(“Held”) I’m aware there are tutorials about this but im not sure how I can implement my code into them. In the explorer I have a remote event image and a cooldown script which doesn’t matter that much. This is the local script

function onButton1Down(mouse)
	if script.Parent.Cooldown.Value == 0 then
		script.Parent.RemoteEvent:FireServer()
		script.Parent.Cooldown.Value = 7
	else
		return
	end
end

function onSelected(mouse)
	mouse.Button1Down:connect(function() onButton1Down(mouse) end)
end

script.Parent.Selected:connect(onSelected)

It fires the remote event after a given time and then the script detects it and executes this code:

local UserInputService = game:GetService("UserInputService")
local Tool = script.Parent.Parent
local play = Tool.Parent.Parent
local char = play.Character
local hum = char.Humanoid 
local root = char.HumanoidRootPart

script.Parent.Parent.RemoteEvent.OnServerEvent:Connect(function(player)
	local function discharged()
          print("Held")
	end
	
	local function charged()
		print("NotHeld")
	end	

end)

I don’t know where and how to add something which detects when the mouse button is held. My aim is for it to fire the function charged when its held and if its not it fires discharged.

3 Likes

GUI / UI Buttons have a built-in event called .MouseButton1Click, which is fired once the player clicks the respective UI, meaning I don’t think you really need to use the mouse and check whether or not is the UI being pressed. (Note: I assume the GUI / UI is a button, otherwise, this won’t work.)

function FireRemoteEvent()
	if script.Parent.Cooldown.Value == 0 then -- If has no cooldown, below.
		script.Parent.RemoteEvent:FireServer() -- Fires the remote event
		script.Parent.Cooldown.Value = 7 -- Restarts the cooldown
	else -- If there is a cooldown, run below.
		return -- Cancel
	end
end

Gui.MouseButton1Down:Connect(FireRemoteEvent) -- On GUI / UI is clicked with 1st mouse button, run function FireRemoteEvent

You could do something like this:

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()

local mouseDown = false

Mouse.Button1Down:Connect(function()
mouseDown = true
end)

Mouse.Button1Up:Connect(function()
mouseDown = false
end)

game:GetService("RunService").Heartbeat:Connect(function()
if mouseDown then
print("Mouse is down")
end
end)
2 Likes