Problem with ai script

I have this ai script which I fixed earlier, it works technically and works the way I want it to but my problem
is that it works for one of the enemies in the folder and it works for a specific one. How would I fix it and make sure it works for all the enemies, heres the script


local pathfinding = game:GetService("PathfindingService")

for _, npc in ipairs(script.Parent:GetChildren()) do
	if npc:IsA("Model") and npc:FindFirstChild("Zombie") then
		local tank = npc
		local humanoid = tank:FindFirstChild("Zombie")
		local rightArm = tank:FindFirstChild("Right Arm")
		local path = pathfinding:CreatePath()
		local players = {}
		local alerted = tank.Alerted.Value 
		local lastDamageTime = 0

		humanoid.Health = health
		humanoid.MaxHealth = health
		humanoid.WalkSpeed = speed

		while wait() do
			local nearestPlayer = nil
			local nearestDistance = radius

			for _, child in pairs(workspace:GetChildren()) do
				if child:IsA("Model") and child:FindFirstChild("Humanoid") then
					local distance = (rightArm.Position - child.HumanoidRootPart.Position).magnitude
					if distance < radius then
						table.insert(players, child)
						if distance < nearestDistance then
							nearestPlayer = child
							nearestDistance = distance
							
							humanoid:MoveTo(nearestPlayer.HumanoidRootPart.Position)
						end
					end
				end
			end

It is only working with one because your while loop is holding up the for loop.
The for loop can’t continue to the next element until all the lines/tasks within the loop are completed, including the while loop (which obviously won’t happen because it is an infinite loop). You can either make a separate script for each enemy, or you could use something such as spawn() or a coroutine (however, too many fast while loops in a coroutine can cause some serious lag issues).

I know about coroutines but how would I be able to use spawn() for this

You can do something like

spawn(function()
     -- Your code here
end)

The lines within the spawn function will not yield the rest of the script.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.