So I am working on a game and I added simple follow AI so an NPC follows the nearest player. The ai Spawns randomly in in randomly generated rooms when the AI does spawn they don't move.
Here is the code
local humanoid = script.Parent.Humanoid
local HRP = script.Parent.HumanoidRootPart
local pathfindingservice = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local maxDistance = 40
local destination = nil
repeat wait() until script.Parent == workspace
while true do
wait(0.016)
local nearestPlayer, nearestDistance
for _, player in pairs(Players:GetPlayers()) do
local character = player.Character
local distance = player:DistanceFromCharacter(HRP.Position)
if not character or
distance > maxDistance or
(nearestDistance and distance >= nearestDistance)
then
continue
end
nearestDistance = distance
nearestPlayer = player
end
print("The nearest player is ", nearestPlayer)
if nearestPlayer ~= nil then
humanoid:MoveTo(nearestPlayer.Character.HumanoidRootPart.Position)
end
end
I don't know why it is not working.

2 comments
That is what line 12 is for.
If the ai is going into workspace but then not working I am not sure what is wrong, I have been having problems w/ pathfinding too, it could be a bug.