Why isn't the game detecting when I am chatting?

Greetings fellow devs,
So I’ve been making something and I run into a problem. I want to create a part of a script which only runs when the player is not chatting. However this does not work.

Here is the script:

--Script made by Theyoloman1920

--Services

local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")

--Variables

local plr = game.Players.LocalPlayer
local chatting = false

--Funtions

local function startChatting()
	chatting = true
end

local function endChatting()
	chatting = false
end

--Excecutions

UserInputService.TextBoxFocused:Connect(startChatting)
UserInputService.TextBoxFocusReleased:Connect(endChatting)

if not chatting then
	UserInputService.InputBegan:Connect(function(inputObject, gameProcessedEvent)
		if inputObject.KeyCode == Enum.KeyCode.W then
			print("Go Front")
		elseif inputObject.KeyCode == Enum.KeyCode.A then
			print("Go Left")
		elseif inputObject.KeyCode == Enum.KeyCode.S then
			print("Go Back")
		elseif inputObject.KeyCode == Enum.KeyCode.D then
			print("Go Right")
		end
	end)
end

The last part is the part we care about.

It’s still detecting output while I am writing in the chat. Unfortunately, the forum is not allowing me to post the video file saying that there was an error, but I think you get the idea of what i want to archive and what happens.

Thnx
-Yolo

The compiler reads “Is not chatting?” when the script first runs. You likely aren’t fast enough to be chatting by the time the compiler reads that, so it’s true. Since it’s true, you then connect the InputBegan event to that function. That function now runs EVERY TIME there is input. The compiler won’t go up lines to re-read the conditional. Reformat the connected code to look like this:

UserInputService.InputBegan:Connect(function(inputObject, gameProcessedEvent)
	if gameProcessedEvent or chatting then return end

	if inputObject.KeyCode == Enum.KeyCode.W then
		print("Go Front")
	elseif inputObject.KeyCode == Enum.KeyCode.A then
		print("Go Left")
	elseif inputObject.KeyCode == Enum.KeyCode.S then
		print("Go Back")
	elseif inputObject.KeyCode == Enum.KeyCode.D then
		print("Go Right")
	end
end)
2 Likes

Yup worked. Thanks for your very explanatory reply. I appreciate it! :upside_down_face:

1 Like