Stop keycode input scripts while typing

I have a custom chat system I have made but when I type the letters asdw in it the player moves. How can I stop this while the player is typing.

8Ad2pgw89n

A script to listen for the key “S”. I tried making it work but I dosen’t and there are no errors.

KeyHeld = false

function onKeyPress(inputObject,gameProcessed)
	if inputObject.KeyCode == Enum.KeyCode.S then
		KeyHeld = true
		while KeyHeld == true do
			wait()
			if script.Parent.Parent.PlayerGui.MainUi.Chat.TextBox.IsFocused == true then
			else
				game.ReplicatedStorage.Movement.MoveDown:FireServer()  
			end
end
end
end

function onKeyRelease(inputObject,gameProcessed)
	if inputObject.KeyCode == Enum.KeyCode.S then
		KeyHeld = false
	end
end

game:GetService("UserInputService").InputBegan:connect(onKeyPress)
game:GetService("UserInputService").InputEnded:connect(onKeyRelease)
2 Likes

I would recommend using Context Action Service rather than User Input Service as Context Action Service was designed for these types of problems.
https://developer.roblox.com/en-us/api-reference/class/ContextActionService
This might help.

I have a custom movement system that is fully 2d I dont think this would work as that for player interactions like sitting, holding tools ect

1 Like

I have fixed the issue, Heres what I tried for anyone wandering:

KeyHeld = false
local UserInputService = game:GetService("UserInputService")

function onKeyPress(inputObject,gameProcessed)
	if inputObject.KeyCode == Enum.KeyCode.S then
		KeyHeld = true
		while KeyHeld == true do
			wait()
			if not UserInputService:GetFocusedTextBox(script.Parent.Parent.PlayerGui.MainUi.Chat.TextBox) then
				game.ReplicatedStorage.Movement.MoveDown:FireServer()  
			end
		end
	end
end

function onKeyRelease(inputObject,gameProcessed)
	if inputObject.KeyCode == Enum.KeyCode.S then
		KeyHeld = false
	end
end

game:GetService("UserInputService").InputBegan:connect(onKeyPress)
game:GetService("UserInputService").InputEnded:connect(onKeyRelease)

You could of also used gameProcessed, that is either true or false depending if the user is focused on any UI that captured his keyboard.

1 Like