Loop doesnt break

Hi, Im trying to make a loop that breaks when you press the key Z. But for some reason the method Im currently trying doesnt work, along with a few others I tried.

repeat Input = game.UserInputService.InputBegan:Wait() until Input == Enum.KeyCode.Z

Help would be appreciated!

Check out this post, I believe it has what you’re looking for.

local UserInputService = game:GetService("UserInputService")

local Pressed = false

UserInputService.InputBegan:Connect(function(key, gpe)
    if gpe == false then
        if key.KeyCode.Name == "Z" then
            Pressed = true
        end
    end
end)

while true do
    if Pressed == true then
        break
    end
    task.wait()
end
1 Like

The post I sent shows basically this.

or just do

while not Pressed do
	task.wait()
end

Try initializing “Input” before the loop.

I don’t really understand why you’re using loops in the first place at all though.

Yeah, if we’re talking about detecting when the Z is pressed, they could just do the following:

local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(input, processed)
    if processed then
        return
    end
    
    if input.KeyCode == Enum.KeyCode.Z then
        -- do whatever here
    end
end)

Im trying to yield the script until the key is pressed and thought this was a more optimized way of checking if the key has been pressed or not.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.