Just want to know the function/line for when the mouse is held down, and able to know when it is held and when it is brought back up again. Sorry if this has already been asked, I couldn't find it, thanks.
How to detect the mouse being held down?
3 answers
ROBLOX doesn't have a built in way to determine this, but writing it yourself is very easy.
The intuition is that a button is held down for the time between pressing it and releasing it.
mouseDown = false
startedDown = 0
-- `mouse` a Mouse object from, e.g., theLocalPlayer:GetMouse()
mouse.Button1Down:connect( function()
mouseDown = true
-- From now on, held
startedDown = tick() -- Current time, in seconds
end)
mouse.Button1Up:connect( function()
mouseDown = false
-- From now on, NOT held
end)
while wait() do
if mouseDown then
print(
"Has been held for ",
tick() - startedDown,
-- Time between now and when `startedDown` was set
"seconds"
)
else
print("Not held.")
end
end
Alright, so while BlueTaslem's code works, I think this way is a bit more elegant, although, me being a really bad coder, his is probably more efficient or whatever..
inptSrvc = game:GetService("UserInputService")
while true do
if inptSrvc:IsMouseButtonPressed(0) then
--Your script
end
end
"--Your script" will run while the left mouse button is being held
1 comment
There is a problem with your script, and that is, if the player stops holding down the mousebutton, you cannot end the event that you have placed. So I recommend adding an elseif not function as well.
As RarePlutonian said, The working script should be the following, Tho you have to cancel the script if the button isn't being held. That is very simple you can just do
inptSrvc = game:GetService("UserInputService")
while true do
if inptSrvc:IsMouseButtonPressed(0) then
--Your script
else
print('Not being held')
end
end
1 comment
you can change the ELSE code into something else it doesn't matter as long as it workss
This discussion is preserved as it was. New answers, comments, and votes are closed.

5 comments
One question, how would I check if it has been held for, say, 3 seconds
Another variable that stores the time (time(), tick() or os.time()), and the difference between the current time and the stored time is how long it was held.
Sorry, you have lost me, however if you could provide an answer that just does what you said, then i'll upvote it.
Answer amended to include the time held for.
Thank you