Hi! So I’m trying to make this system where an NPC follows the nearest player. However, I’m also trying to make the NPC stop following the player once the target has died.
Problem: Even though the player has died, the NPC won’t stop moving until the character is actually gone.
I tried using humanoid:MoveTo(rootPart)
but it did not work. I’m not sure if I might have placed it in the wrong section.
Any suggestions to fix this are appreciated.
The script in ServerScriptService
local players = game:GetService("Players")
local runService = game:GetService("RunService")
local npcs = workspace:WaitForChild("NPCs")
local targets = {}
players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(char)
table.insert(targets, char)
char:WaitForChild("Humanoid").Died:Connect(function()
table.remove(targets, table.find(targets, char))
end)
end)
player.CharacterRemoving:Connect(function(char)
table.remove(targets, table.find(targets, char))
end)
end)
local function getNearestPlayer(npc)
if not npc:FindFirstChild("Humanoid") then return end
if #players:GetPlayers() < 1 then
print("no players found.")
end
repeat wait() until #players:GetPlayers() >= 1
repeat wait() until #targets > 0
local closest
local currentPos = npc.PrimaryPart.Position
local currentTarget = nil
table.sort(targets, function(a, b)
return (npc.PrimaryPart.Position - a.PrimaryPart.Position).Magnitude < (npc.PrimaryPart.Position - b.PrimaryPart.Position).Magnitude
end)
closest = targets[1]
currentTarget = closest
currentPos = npc.PrimaryPart.Position
closest:WaitForChild("Humanoid").Died:Connect(function()
currentTarget = nil
table.remove(targets, 1)
if #targets == 0 then
print("no players found.")
npc.Humanoid:MoveTo(npc.HumanoidRootPart.Position)
return nil
end
closest = targets[1]
end)
return closest
end
local function moveNPCToClosest(npc)
local closestPlayer = getNearestPlayer(npc)
repeat wait() until closestPlayer ~= nil
npc.Humanoid:MoveTo(closestPlayer.PrimaryPart.Position)
end
runService.Heartbeat:Connect(function()
for _, npc in pairs(npcs:GetChildren()) do
if npc:IsA("Model") and npc:FindFirstChild("Humanoid") then
moveNPCToClosest(npc)
end
end
end)