How to check if mousebutton1 is being held

So I’m making a mining game, and I need to know how to check if mousebutton1 is being held down and if so, do a function. How would I go about doing this? I tried iskeydown but it won’t work(not really a surprise, its all I had in mind) Thanks, AX1T

1 Like

My Solution:


All you need is a simple variable. Like:

local isHoldingMouseDown = false

mouseButton1Down:Connect(function()
isHoldingMouseDown = true
end)

mouseButton1Up:Connect(function()
isHoldingMouseDown = false
end)

For the mining it self you can do: (While the mouse is being held down)

spawn(function()
while while isHoldingMouseDown == true do 
-- Code
-- Run Animation

--
end
end)
2 Likes

try getting the player mouse and do

 local clicked = false

mouse.Button1Down:connect(function()
      clicked = true
end)

mouse.Button1Up:connect(function()
       clicked = false
end)

thanks to you both. I appreciate it

1 Like

I would recommend using UserInputService for this. It’s the most reliable and better than the methods described above.

You would connect it to two events. InputBegan and InputEnded and check if the input is the mouse.

--// Services
local UserInputService = game:GetService("UserInputService")

--// Objects
local Held = false

UserInputService.InputBegan:Connect(function(inputObject)
	if inputObject.UserInputType == Enum.UserInputType.MouseButton1 then
		Held = true
	end
end)

UserInputService.InputEnded:Connect(function(inputObject)
	if inputObject.UserInputType == Enum.UserInputType.MouseButton1 then
		Held = false
	end
end)

while wait() do
	print(Held)
end
4 Likes

I’m gonna use uis then, I knew it was possible but I didn’t know how. Thanks .

instead of while true do try using render stepped

It is still the same concept. But UIS will work as well.

Im not doing while true do, Im using a condition. While Condition Do. This is better then using RenderStepped. That’d be just be unnecessarily running code.

2 Likes

If you’re only connecting for the sake of detecting when a key is held, you can shorthand this to InputChanged.

UserInputService.InputChanged:Connect(function (InputObject, EventProcessed)
    if InputObject.UserInputType == Enum.UserInputType.MouseButton1 then
        Held = (InputObject.UserInputState == Enum.UserInputState.Begin)
    end
end)

Not much of a difference and ultimately you should pick whichever is readable to you, but I feel that connections only meant to be registered for single-actions can be handled in one function.

1 Like