'Npc not moving to waypoints in order?

Ive been trying to move an npc to a waypoint in order, it worked for a bit but then it starts moving out of order and is starting to act weird

Waypoints: enter image description here

Move script:

for i,node in pairs(script.Parent.Parent.Parent.Cartnodes:GetChildren()) do
if node:IsA("BasePart") then
    print(node.Name)
    script.Parent.Parent:WaitForChild("Rafthuman"):MoveTo(node.Position)
    

    script.Parent.Parent:WaitForChild("Rafthuman").MoveToFinished:Wait()
    
    node:Destroy()
end
end


Solution 1:[1]

Unintuitively, the order of the children is not determined by alphabetical order. If you look at the docs for Instance:GetGhildren(), you'll see this note :

The children are sorted by the order in which their Parent property was set to the object.

So to get them in the right order, you'll need to sort the list before iterating over it.

local raftHuman = script.Parent.Parent:WaitForChild("Rafthuman")
local nodes = script.Parent.Parent.Parent.Cartnodes
local children = nodes:GetChildren()
local sortedChildren = table.sort(children, function(a, b) 
    return a.Name < b.Name
end)
for i,node in ipairs(sortedChildren) do
    if node:IsA("BasePart") then
        print(node.Name)
        raftHuman:MoveTo(node.Position)
        raftHuman.MoveToFinished:Wait()
        node:Destroy()
    end
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kylaaa