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.
You need to disable the script until the NPC is in workspace, this is because the NPC cannot have a position in Server Storage. (Line 19) The script cannot find the player nearest to the NPC without the position of the NPC.