Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Any way to get the event of the mouse button being held down?

I'd like to know if there's an event for TextButtons/ImageButtons that fire when the left mouse button is held down, as in you hold it down for a couple of seconds. I know MouseButton1Down, but that's not suiting for what I'm trying to do. What I'm trying to do is while the left mouse button is held down, a dummy model is rotated. The current script only fires when the mouse is clicked and not held down.

local dummy = workspace.Dummy
script.Parent.MouseButton1Click:Connect(function()
	dummy:SetPrimaryPartCFrame(dummy.PrimaryPart.CFrame * CFrame.fromEulerAnglesXYZ(0,math.rad(3),0))
end)

2 answers

Not sure if there's any easier way to do it, but all I've found was using UserInputService

local inputService = game:GetService("UserInptuService")

local mouseDown = false

inputService.InputBegan:Connect(function(input)) 
	if(input.UserInputType == Enum.UserInputType.MouseButton1) then
		mouseDown = true
		while mouseDown == true do 
			-- your code
		end
	end
end)

inputService.InputEnded:Connect(function(input)
	if(iinput.UserInputType == Enum.UserInputType.MouseButton1) then
		mouseDown = false
	end
end

Explained:

	if(input.UserInputType == Enum.UserInputType.MouseButton1) then

Checks if the key pressed is the mouse's right button

mouseDown = true
		while mouseDown == true do 
			-- your code
		end

changes the "mouseDown" variable's value to true, and lets your things happen while it's down/being held

inputService.InputEnded:Connect(function(input)
	if(iinput.UserInputType == Enum.UserInputType.MouseButton1) then
		mouseDown = false
	end
end

Detects when the mouse button is no longer being held, and when it does, changes the variable's value, stopping the loop

Let me know if you need any extra help!

2 comments

1

Alternatively you set a value to true/false and do while that value. Set true when MouseButton1Down, and set false when MouseButton1Up

0

Hadn't thought about that, good idea!

While UserInputService is good to know, this might be an easier way to understand.

m1down = false

function doThing()
  while m1down do
    --Thing
    wait()
  end
end

script.Parent.MouseButton1Down:Connect(function() m1down = true doThing() end)
script.Parent.MouseButton1Up:Connect(function() m1down = false end)


This discussion is preserved as it was. New answers, comments, and votes are closed.