Npc repeating the same line even if detecting a different chat command

I tried to make an NPC that can converse with the player in a certain distance and will respond depending on what the player said

well the problem is…

The NPC keeps repeating the same line over and over again, even if they detect a different string. Sometimes, they repeat the line even if the player says nothing close to the preset line. What is going on here?

script
local tcs = game:GetService("Chat")
local plr = game:GetService("Players")

local hrp = script.Parent

local chatCD = false

plr.PlayerAdded:Connect(function(Player)
	Player.Chatted:Connect(function(msg)
		if chatCD then return end
		local Distance = (hrp.Position - Player.Character.HumanoidRootPart.Position).Magnitude
		if Distance <= 10 then
			if string.find(msg, "Hi") or string.find(msg, "Hello") or string.find(msg, "Hi?") or string.find(msg, "Hello?") -- cap
				or string.find(msg, "hi") or string.find(msg, "hello") or string.find(msg, "hi?") or string.find(msg, "hello?") -- nocap
			then
				chatCD = true
				task.wait(1.5)
				tcs:Chat(hrp, "I was waiting for you")
				chatCD = false
			elseif string.find(msg, "Who are you") or string.find(msg, "Who are you?") -- cap
				or string.find(msg, "who are you") or string.find(msg, "who are you?") -- nocap
			then
				chatCD = true
				task.wait(1.5)
				tcs:Chat(hrp, "That doesn't matter")
				chatCD = false
			end
		end
	end)
end)

Instead of using string.find, use string.lower to lower the letters instead of typing it all in a new line.

local tcs = game:GetService("Chat")
local plr = game:GetService("Players")

local hrp = script.Parent

local chatCD = false

plr.PlayerAdded:Connect(function(Player)
	Player.Chatted:Connect(function(msg)
		if chatCD then return end
		local Distance = (hrp.Position - Player.Character.HumanoidRootPart.Position).Magnitude
		if Distance <= 10 then
			if string.lower(msg) == "hi" or string.lower(msg) == "hello" or string.lower(msg) == "hi?" or string.lower(msg) == "hello?" then
				chatCD = true
				task.wait(1.5)
				tcs:Chat(hrp, "I was waiting for you")
				chatCD = false
			elseif string.lower(msg) == "who are you" or string.lower(msg) == "who are you?" then
				chatCD = true
				task.wait(1.5)
				tcs:Chat(hrp, "That doesn't matter")
				chatCD = false
			end
		end
	end)
end)
1 Like

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