Here my code:
local units = {}
local createUnitModule = require(script.Parent.modules.unit_module.unitHandler)
local path = nil
local Waypoints = nil
local Gsuccess = nil
local Gerr = nil
game.ReplicatedStorage.remotes.createUnitMessage.OnServerEvent:Connect(function(plr, unitname)
local unit = createUnitModule.createUnit(plr, unitname)
print(unit)
if not unit then
return false
else
if units[plr] == nil then
units[plr] = {}
end
table.insert(units[plr], unit)
end
end)
game.ReplicatedStorage:WaitForChild("MoveUnit").OnServerEvent:Connect(function(player, v, hum, MouseV3pos)
if units[player] == nil then
return
end
local Glit = hum.Parent.Parent
if not Glit or Glit.Name ~= "HitBox" then
return
end
local indexNPC = Glit.Parent
local isplrhasthisnpc = false
for i, v in pairs(units[player]) do
if v.index == indexNPC and v.owner == player then
isplrhasthisnpc = true
break
end
end
if not isplrhasthisnpc then
return
end
local PathfindingService = game:GetService("PathfindingService")
local NPC = Glit:FindFirstChildOfClass("Model")
local humRP = NPC:WaitForChild("HumanoidRootPart")
local reachedConnection
local Target = MouseV3pos
local humanoid = NPC.Humanoid
Gsuccess = nil
local function walkTo(targetPosition)
Waypoints = nil
path = nil
local success = nil
local err = nil
while not success do
success, err = pcall(function()
path = PathfindingService:CreatePath()
path:ComputeAsync(humRP.Position, targetPosition)
Waypoints = path:GetWaypoints()
end)
end
local success = nil
local err = nil
while not success do
success, err = pcall(function()
for i, waypoint in pairs(Waypoints) do
if Waypoints then
print("norm")
humanoid:MoveTo(waypoint.Position)
humanoid.MoveToFinished:Wait(0.4)
end
end
end)
end
if Waypoints then
humanoid:MoveTo(targetPosition)
humanoid.MoveToFinished:Connect(function()
Gsuccess = true
wait(1)
end)
end
end
while not Gsuccess do
walkTo(Target)
end
end)
As I understand it, the waypoints stack up. But how I can fix it??