How to make a enemy continue the path of the first enemy

https://i.gyazo.com/9de1858f50f9bb22a63e1db69b1be022.gif

I’m trying to make a necromancer mob, i’m having issues when it spawns another mob, the mob just tries to go the first waypoint instead of just continue from the necromancer position

the script:

local replicatedStorage = game:GetService('ReplicatedStorage')
local pathFindingService = game:GetService('PathfindingService')
local tweenService = game:GetService('TweenService')
local assets = replicatedStorage:FindFirstChild('Assets')
local enemies = assets:FindFirstChild('Enemies')
local gameFolder = workspace:FindFirstChild('Game')
local mapFolder = gameFolder:FindFirstChild('Map')
local map = mapFolder:FindFirstChild('Map')
local waypoints = map:FindFirstChild('Waypoints')
local enemiesFolder = gameFolder:FindFirstChild('Enemies')
local module = {}

function module.moveTo(enemy)
	local enemyspawner
	
	enemy.ChildAdded:Connect(function(child)
		if child.Name == 'spawnedBy' then
			if enemy:FindFirstChild('spawnedBy') then
				enemyspawner = enemy:FindFirstChild('spawnedBy').Value
				enemy:FindFirstChild('nextWaypoint').Value = enemyspawner:FindFirstChild('nextWaypoint').Value
				print('nextWaypoint', enemy:FindFirstChild('nextWaypoint').Value)
			end
		end
	end)
	
	for waypoint = enemy:FindFirstChild('nextWaypoint').Value, #waypoints:GetChildren() do
		local createPath = pathFindingService:CreatePath()
		createPath:ComputeAsync(enemy.PrimaryPart.Position, waypoints[waypoint].Position)
		
		enemy:FindFirstChild('nextWaypoint').Value = waypoint
		
		print(enemy:FindFirstChild('nextWaypoint').Value)
		
		for i, w in pairs(createPath:GetWaypoints()) do
			enemy.Humanoid:MoveTo(w.Position)
			enemy.Humanoid.MoveToFinished:Wait()
		end
	end
	enemy:Destroy()
end

function module.generateEnemy(enemyName, spacement, amount, cframe, nextwaypoint)
	local enemy
	for i = 1, amount do
		if enemies:FindFirstChild(enemyName) then
			enemy = enemies:FindFirstChild(enemyName):Clone()
			enemy.Parent = enemiesFolder
			enemy.PrimaryPart.CFrame = cframe
			
			
			if not enemy:FindFirstChild('nextWaypoint') then
				local nextWaypoint = Instance.new('StringValue')
				nextWaypoint.Name = 'nextWaypoint'
				nextWaypoint.Parent = enemy
				nextWaypoint.Value = 1
				
				enemy.ChildAdded:Connect(function(child)
					if child.Name == 'spawnedBy' then
						local enemyspawner = enemy:FindFirstChild('spawnedBy').Value
						nextWaypoint.Value = enemyspawner:FindFirstChild('nextWaypoint').Value
					end
				end)
			end
			
			coroutine.wrap(module.moveTo)(enemy)
			return enemy
		end	
		task.wait(spacement)
	end 
end

return module
1 Like