Why does my mouse hold script not work so well?

local uis = game:GetService("UserInputService")

local down = false

uis.InputEnded:Connect(function(inp,gnp)
	if inp.UserInputType == Enum.UserInputType.MouseButton1 then
		print('up')
		down = false
	end
end)

local usedmain = false
uis.InputBegan:Connect(function(inp,gnp)
	if gnp then return end
	
	if inp.UserInputType == Enum.UserInputType.MouseButton1 then
		local down = true
		while down and wait() do
			print('down')
		end
	end
end)

That’s my script, and the output just keeps repeating “down” even after I released my mouse.

down (x9)
up
down (x39)

What could be the issue?

because of the while loop in the InputBegan event, down is printing every wait(). So it will continuously print down until your mouse is up.

This may be the good script:

local uis = game:GetService("UserInputService")

local down = false

uis.InputEnded:Connect(function(inp,gnp)
	if inp.UserInputType == Enum.UserInputType.MouseButton1 then
		print('up')
		down = false
	end
end)

local usedmain = false
uis.InputBegan:Connect(function(inp,gnp)
	if gnp then return end
	
	if inp.UserInputType == Enum.UserInputType.MouseButton1 then
		down = true
	end
end)

while wait() do
   if down then
		print('down')
   end
end

Isn’t very good to do while loops in Connections.

2 Likes

he’ll have to spawn the loop within a event, or use a coroutine.

If he uses a corountine, every time he uses the mouse it will create a new threat. Which, may be laggy and spawns can be delayed or not even going on.

Spawning didn’t work as well btw

I’ll try this after I eat, and respond

1 Like

You aren’t using the “down” variable that other parts of the code are looking at in line 16,

local down = true

But that creates a local variable, that can only be accessed inside that if statement, it should be

down = true

this will change the down you forward declared at the start of your script.

1 Like

That was it, but what causes this now?

**local down = false

uis.InputBegan:Connect(function(inp,gnp)
	if inp.UserInputType == Enum.UserInputType.MouseButton1 then
		down = true
		while down and wait() do
			print('down')
		end
	end
end)

uis.InputEnded:Connect(function(inp,gnp)
	if inp.UserInputType == Enum.UserInputType.MouseButton1 then
		print('up')
		down = false
	end
end)

Yet the output shows:

down (x4)
up
down

Why is that, even after I release it still detects down once?

you are waiting a little bit after checking if down is true, try this

while down do
	print('down')
	wait()
end
1 Like

This works, thank you all for the help!