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

Need help with this script - key pressing. Script doesn't not work as intended?

This script function properly until it gets akeypressed = false

Q keeps printing despite releasing the Key "q"

d = game:GetService("UserInputService")

local akeypressed = true

d.InputBegan:Connect(function(input,gameProccesedEvent) local akeypressed = true

if input.KeyCode == Enum.KeyCode.Q then

	while akeypressed == true do
			wait()
			print ("q")
	end
end

end)

d.InputEnded:Connect(function(input,gameProccesedEvent)

if input.KeyCode == Enum.KeyCode.Q then
	
	if d.InputEnded then
		
		 akeypressed = false
	end
 

end

end)

1 answer

Hey, so first, you shouldn't put the wait time at the beginning of the loop because it gives it a small fraction of time before completely breaking the loop after akeypressed = false

d.InputBegan:Connect(function(input,gameProccesedEvent) 
	if input.KeyCode == Enum.KeyCode.Q then akeypressed = true
	    while akeypressed 
		do 
			print("q")
			wait()
		end
	end
end)

On the second function,

d.InputEnded:Connect(function(input,gameProccesedEvent)
	if input.KeyCode == Enum.KeyCode.Q then
	 		print("False")
	        akeypressed = false
	end
end)

I optimized it, removing the if d.InputEnded then since I think it's not necessarily needed. So, assuming you wanted it to print out Q when the key is pressed down and stop when the key is released. Hope this answers your question!

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