PathFinding code stops running until NPC reaches destination (MoveToFinished)

Hi! So I have this NPC spawner thingy. It spawns an NPC and then moves it to a location. I have two “problems” with it right now:

  1. How can I do that, after the creation of every npc, the code runs and is not waiting until that NPC arrives to his destination.
    I thought maybe using a coroutine here?
  2. The NPC’s don’t seem that they have the same orientation as the destination parts after they take that corner, how can I make them aligned with the destination parts?
    It doesn’t seem to be the HumanoidRootPart rotated, because when an NPC takes a place before taking the corner, he is not rotated like the ones that had to took the corner.

Video: NPC Spawner

Relevant code:

local storage = game:GetService("ServerStorage")
local PathFindingService = game:GetService("PathfindingService")

local function createNPC()
    local NPC = game.ServerStorage.Clubber:Clone()
    NPC.HumanoidRootPart.CFrame = workspace.NPCAreas.Spawn.CFrame
    NPC.Parent = workspace.NPCAreas.NPCs
    NPC.PrimaryPart:SetNetworkOwner(nil)
    return NPC
end

local function getPath(NPC, destination)
    local PathParameters = {
        ["AgentHeight"] = 5.5,
        ["AgentRadius"] = 2.1,
        ["AgentCanJump"] = false
    }
    
    local path = PathFindingService:CreatePath(PathParameters)
    
    path:ComputeAsync(NPC.HumanoidRootPart.Position, destination)
    
    return path

end

local function walkTo(NPC, destination)
    
    local path = getPath(NPC, destination)
    local humanoid = NPC.Humanoid
    
    for index, waypoint in pairs(path:GetWaypoints()) do
        humanoid:MoveTo(waypoint.Position)
        humanoid.MoveToFinished:Wait()
    end
    
end

local function lineUp()
    
    inLineCount.Value += 1 --how many NPC's are in line
    if inLineCount.Value <= 16 then    
        local NPC = createNPC()    
        local location = chooseLoc() -- this function code not relevant
        walkTo(NPC, location)
        wait()
    else
        print("too many, wait for a place to free up")
    end

end

while true do 
    lineUp()    
end

That’s because your code is waiting until the NPC has reached the finish.
You should remove humanoid.MoveToFinished:Wait() or spawn the walkTo function in another thread if you don’t want this behavior. Learn More

Additionally, once all NPC’s have lined up, your code goes into an infinite loop. You should put the wait() (use task.wait(), it’s identical to RunService.Heartbeat:Wait()) outside of your if statement or use break to stop execution once all NPC’s have lined up. For your orientation issues, you are using :MoveTo() which takes in the position of the part (Vector3) or a part instance, which does not include orientation.

1 Like