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

How to make a user input loop?

How would I make the script print "Hello World!" as long as the space bar is held down? Should I use ContextActionService or UserInputService? Does that even affect it? Here's what I have so far:

function onKeyPress(actionName, userInputState, inputObject)
	while userInputState == Enum.UserInputState.Begin do
		wait()
		print("Hello World!")
	end
end
 
game.ContextActionService:BindAction("keyPress", onKeyPress, false, Enum.KeyCode.Space)

2 comments

0

How does not processed not work? http://wiki.roblox.com/index.php?title=API:Class/UserInputService/InputBegan There is a game processed event.

0

OH NVM Not processed means that it does not run if you're chatting or typing into a textbox.

1 answer

✓ Accepted answer

Instead of using the ContextActionService use UserInputService and a repeat loop.


#InputBegan It will run once there is input, if it's a Regular script, it runs when ANY player does any input. If it's a local script then it only runs once a certain

local userinputservice = game:GetService("UserInputService")

userinputservice.InputBegan:connect(function(key, processed)
	if key.KeyCode == Enum.KeyCode.Space and not processed then --Processed is like, chatting/typing into a textbox.
		print("Pressed space")
	end
end)

#InputEnded This runs once you stop inputting.

local userinputservice = game:GetService("UserInputService")

userinputservice.InputEnded:connect(function(key, processed)
	if key.KeyCode == Enum.KeyCode.Space and not processed then --Processed is like, chatting/typing into a textbox.
		print("Stop pressing space")
	end
end)

#repeat This loops until something is true

local a = 0
repeat
	a = a+1
	wait() --Add some type of yield to prevent game from crashing
until a > 5


#Final Product

local userinputservice = game:GetService("UserInputService")
local looped = false

userinputservice.InputBegan:connect(function(key,processed)
	if key.KeyCode == Enum.KeyCode.Space and not processed then
		looped = true
		repeat
			--Code goes here
			wait()
		until not looped
	end
end)

userinputservice.InputEnded:connect(function(key, processed)
	if key.KeyCode == Enum.KeyCode.Space and not processed then
		looped = false
	end
end)



Hope it helps!

1 comment

0

It doesnt work with "and not processed". If I remove that it works fine. Thank you.

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