Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to make a user input loop?

Asked by 8 years ago

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)
0
How does not processed not work? http://wiki.roblox.com/index.php?title=API:Class/UserInputService/InputBegan There is a game processed event. EzraNehemiah_TF2 3552 — 8y
0
OH NVM Not processed means that it does not run if you're chatting or typing into a textbox. EzraNehemiah_TF2 3552 — 8y

1 answer

Log in to vote
1
Answered by 8 years ago

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!

0
It doesnt work with "and not processed". If I remove that it works fine. Thank you. Orlando777 315 — 8y
Ad

Answer this question