How to make script only activate when text says a specific word?

I have a script that detects a specific TextBox for the text “hi”. If this is present in the TextBox, it should print “works” once when enter is pressed.

But for some reason, hovering the mouse over the text box makes it print works every time the mouse moves, even if “hi” isn’t typed in. Even if “hi” is there, it still spams the print.

local text = script.Parent

text.InputChanged:Connect(function()
	local input = text.Text

	if string.match("hi", input) then
		print("works")
	end
end)

Any way to fix this?

2 Likes

I would use :GetPropertyChangedSignal(“Text”) instead, and string.match(“hi”, input) is returning “” which is why your print is firing. I would recommend using string.find() instead, because it returns nil if it doesn’t match.

Fixed code:

local text = script.Parent

text:GetPropertyChangedSignal("Text"):Connect(function()
	if string.find(text.Text, "hi") then
		print("works")
	end
end)
4 Likes

There is a function called “FocusLost” inside a textbox. Try using this code:

script.Parent.FocusLost:Connect(function(pressedEnter)
	if pressedEnter == true then
		print("hi")
	end
end)
2 Likes

It works, but another question, how can I make it so it only prints when I press Enter?
(something like when Enter is pressed, if what you entered is “hi” it only prints then)

(reason is so it doesn’t fire anything while typing something including the same word)

1 Like

Oh, do you only want it to detect when the text is exactly “hi”?

2 Likes

Yes.

My plan is to make it so when pressing enter, if I make it detect something like “add” for example, it fires a function that adds a part into the workspace (with specific properties like size, color, material, etc.)

1 Like

Alright, try this:

local text = script.Parent

text.FocusLost:Connect(function(enterPressed)
	if not enterPressed or text.Text ~= "hi" then
		return
	end
	
	print("works")
end)
2 Likes

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