I’m trying to learn pathfinding with NPCs. My ideal goal will be to make my zombies follow the nearest player, so the destination location will change. I came across a problem where changing my example destination point makes my NPC lag for no reason after it reached there for the first time. It’s probably caused by my while loop
down below. Does this mean I might be indexing my waypoints wrong?
Here is the script im using:
local ReplicatedFirst = game:GetService('ReplicatedFirst')
local PathfindingService = game:GetService('PathfindingService')
local Zombie = game.Workspace.Walker
local Spawnpoint = game.Workspace.SpawnLocation
local path = PathfindingService:CreatePath()
local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection
local function followPath()
local humanoid = Zombie.Humanoid
local humanoidRootPart = Zombie.HumanoidRootPart
local success, errorMessage = pcall(function()
humanoidRootPart:SetNetworkOwner(nil)
path:ComputeAsync(humanoidRootPart.Position, Spawnpoint.Position)
end)
if success and path.Status == Enum.PathStatus.Success then
waypoints = path:GetWaypoints()
blockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)
if blockedWaypointIndex >= nextWaypointIndex then
blockedConnection:Disconnect()
followPath()
end
end)
if not reachedConnection then
reachedConnection = humanoid.MoveToFinished:Connect(function(reached)
if reached and nextWaypointIndex < #waypoints then
nextWaypointIndex += 1
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
reachedConnection:Disconnect()
blockedConnection:Disconnect()
end
end)
end
nextWaypointIndex = 2
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
end
end
while task.wait(.2) do
followPath()
end