AI Code not working

I am trying to create an AI that goes towards the nearest player, but the code won’t work.

Error:

Workspace.CustomAI.Script:17: Script timeout: exhausted allowed execution time - Server - Script:8

Code:

local players = game.Players
local AI = script.Parent

local hum = AI:WaitForChild("Humanoid")


local function locate()
	for i, player in pairs(players:GetChildren()) do
		task.wait(0.1)
		hum:MoveTo(player:WaitForChild("HumanoidRootPart").Position)
	end
end

while true do
	locate()
end 

Any help is appreciated!

1 Like

Your code has multiple issues.

for i, player in pairs(players:GetChildren()) do
	task.wait(0.1)
	hum:MoveTo(player:WaitForChild("HumanoidRootPart").Position)
end

This will move to every player every 1/10 of a second. Instead, you need to locate the nearest player (or whatever critera you are looking for to find a specific target) and move towards only them. A simpel check could involving finding the nearest player through checking every player’s magnitude distance from the AI

while true do locate() end

Please throw a task.wait() in there. This is a surefire way to crash your server.

You need to add a wait inside the while loop.

2 Likes

Try this:

local players = game.Players
local AI = script.Parent

local hum = AI:WaitForChild(“Humanoid”)

local function locate()
for i, player in pairs(players:GetChildren()) do
task.wait(0.1)
hum:MoveTo(player[i]:WaitForChild(“HumanoidRootPart”).Position)
end
end

while true do
locate()
end