Mouse hold detection?

How can I make a localscript detect if the player is holding their mouse down or not?

Use UserInputService’s InputBegan and InputEnded events and set a boolean variable to either true or false.

example

local uis = game:GetService("UserInputService")
local isHolding = false -- variable to determine if the player is holding their mouse down

uis.InputBegan:Connect(function(io, gp)
   if gp then return end -- the button is being synced with something else, so stop the function

   if io.UserInputType == Enum.UserInputType.MosueButton1 then -- check if the key is correct
      isHolding = true -- set the variable to true
   end
end)

uis.InputEnded:Connect(function(io, gp)
   if gp then return end

   if io.UserInputType == Enum.UserInputType.MosueButton1 then
      isHolding = false -- set the variable to false
   end
end)

In addition, you can use ContexActionService.

Context Action Service example

local cas = game:GetService("ContextActionService")
local isHolding = false -- same thing as the previous example

local function myFunction(name, state, object) -- function to bind it to
    -- these are the three parameters that ContextActionService sends to the function

    if state == Enum.UserInputState.Begin then
       -- the player started holding their mouse down
       isHolding = true
    elseif state == Enum.UserInputState.End then
       -- the player stopped holding their mouse down
       isHolding = false
    end

    return Enum.ContextActionResult.Pass -- return that it passed
end

--        action name   function  mobile btn           keycodes
cas:BindAction("mouse", myFunction, false, Enum.UserInputType.MouseButton1)
-- bind the action so it can be called everytime the button is pressed
2 Likes