How can I improve this Zombie AI

Script:

local myHuman = script.Parent:WaitForChild("Humanoid")
local myRoot = script.Parent:WaitForChild("HumanoidRootPart")

while true do
	local target
	local dist = 200
	
	for i, plr in pairs(game.Players:GetPlayers()) do
		local v = workspace:FindFirstChild(plr.Name)
		if v then
			local human = v:FindFirstChild("Humanoid")
			local rootPart = v:FindFirstChild("HumanoidRootPart")
			if human and rootPart and v ~= script.Parent then
				if (myRoot.Position - rootPart.Position).magnitude <= dist and human.Health > 0 then
					dist = (myRoot.Position - rootPart.Position).magnitude
					target = rootPart
				end
			end
		end
	end
	
	if target then
		local damageDebounce = true
		
		local damageCor = coroutine.wrap(function()
			while true do
				wait()
				repeat wait() until (myRoot.Position - target.Position).magnitude <= 3
				myHuman.WalkSpeed = 0
				wait(.5)
				
				local human2 = target.Parent:FindFirstChild("Humanoid")
				if human2 and damageDebounce == true then
					damageDebounce = false
					human2:TakeDamage(10)
					wait(1)
					damageDebounce = true
				end
				myHuman.WalkSpeed = 16
			end
		end)
		damageCor()
		
		local ray = Ray.new(myRoot.Position, (target.Position - myRoot.Position).Unit * 200)
		local hit, position = workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent}, false, true)
		
		if hit then
			if hit.Parent:IsDescendantOf(target.Parent) then
				myHuman:MoveTo(target.Position)
			else -- Pathfinder script starts
				local path = game:GetService("PathfindingService"):CreatePath()
				path:ComputeAsync(myRoot.Position, target.Position)
				
				if path.Status == Enum.PathStatus.Success then
					for i,v in pairs(path:GetWaypoints()) do
						myHuman:MoveTo(v.Position)
						
						if v.Action == Enum.PathWaypointAction.Jump then
							myHuman.Jump = true
						end
						
						myHuman.MoveToFinished:Wait(2)
					end
				else
					warn(script.Parent.Name.." cannot reach destination.")
					myHuman.Jump = true
				end
			end
		end
	else
		local x = math.random(-100, 100)
		local z = math.random(-100, 100)
		
		local pos = Vector3.new(x, 0 ,z)
		
		local path = game:GetService("PathfindingService"):CreatePath()
		path:ComputeAsync(myRoot.Position, pos)
		
		if path.Status == Enum.PathStatus.Success then
			for i,v in pairs(path:GetWaypoints()) do
				myHuman:MoveTo(v.Position)
				
				if v.Action == Enum.PathWaypointAction.Jump then
					myHuman.Jump = true
				end
				
				myHuman.MoveToFinished:Wait(2)
			end
		else
			myHuman.Jump = true
		end
	end
	
	wait()
end
1 Like

Wrong category! Move it to #help-and-feedback:scripting-support

1 Like

You should actually move it to #help-and-feedback:code-review.