Hello Xeilot,
First, let's define a chat function for you to use:
local chatService = game:GetService("Chat")
function chat(part,msg,color)
chatService:Chat(part,msg,color or Enum.ChatColor.White)
end
This allows you to make any part you want chat. We define the chat service outside of the function so we don't have to get it every time we use the function.
After that, we'll create a checkMessage function to check valid messages, and have the NPC reply.
local messages =
{
["player message here"] = "NPC Response here",
}
function checkMessage(msg)
msg = string.lower(msg)
local response = messages[msg]
if response then
chat(npc.Head,response)
end
end
Next, we need to check for player chats. This one is a bit more tricky, but overall pretty easy.
local plrs = game:GetService("Players")
function playerAdded(plr)
end
plrs.PlayerAdded:Connect(playerAdded)
Inside that function we can check when a player has chatted.
local plrs = game:GetService("Players")
function playerAdded(plr)
plr.Chatted:Connect(function(message,reciever)
if plr.Character then
if not reciever then
local distance = (plr.Character:GetPrimaryPartCFrame().p-npc:GetPrimaryPartCFrame.p)
if distance < 10 then
checkMessage(message)
end
end
end
end
end
plrs.PlayerAdded:Connect(playerAdded)
Now that we have those three components, let's define our NPC.
local npc = script.Parent
We're done! Now we can combine it into one script:
local chatService = game:GetService("Chat")
local plrs = game:GetService("Players")
local messages =
{
["player message here"] = "NPC Response here",
}
function chat(part,msg,color)
chatService:Chat(part,msg,color or Enum.ChatColor.White)
end
function checkMessage(msg)
msg = string.lower(msg)
local response = messages[msg]
if response then
chat(npc.Head,response)
end
end
function playerAdded(plr)
plr.Chatted:Connect(function(message,reciever)
if plr.Character then
if not reciever then
local plrPos= plr.Character:GetPrimaryPartCFrame().p
local npcPos = npc:GetPrimaryPartCFrame().p
local distance = (plrPos-npcPos).magnitude
if distance < 10 then
checkMessage(message)
end
end
end
end
end
plrs.PlayerAdded:Connect(playerAdded)
And we're done! The NPC now can detect when a player chats, check the distance between it and the player, and then reply!
If you've got any questions, feel free to ask me.
2 comments
When I try putting that in, it says the last end has a red line under it
and it doesn't seem to work