Hello there,
I’m making an AI that will catch you if it sees you, but the script give me an error that says Script timeout: exhausted allowed execution time
. Idk why that happens. I tried changing the script from:
while wait(0.25) do
patrol()
end
to
while true do
patrol()
wait(0.25)
end
and it still give me the same result but on different line.
Here is the full script!
local ai = script.Parent
local humanoid = ai.Humanoid
local root = ai.HumanoidRootPart
local currentTarget = nil
local function findTarget()
local players = game.Players:GetPlayers()
local maxDistance = 500
local nearestTarget
for index, player in pairs(players) do
if player.Character then
local target = player.Character
local distance = (root.Position - target.PrimaryPart.Position).magnitude
if distance <= maxDistance then
maxDistance = distance
nearestTarget = target
end
end
end
return nearestTarget
end
local function canSeeTarget(target)
local origin = root.Position
local direction = (target.PrimaryPart.Position - root.Position).unit * 500
local ray = Ray.new(origin, direction)
local ignoreList = {ai, ai.Parent:WaitForChild("Doors")}
local hit, pos = workspace:FindPartOnRayWithIgnoreList(ray, ignoreList)
if hit then
if hit:IsDescendantOf(target) then
local x = math.abs(hit.Position.Y - root.Position.Y) < 2
if x then
return true
else
return false
end
else
return false
end
else
return false
end
end
local function getPath(destination)
local PathfindingService = game:GetService("PathfindingService")
local parameters = {
AgentHeight = 7,
AgentRadius = 4,
AgentCanJump = true
}
local path = PathfindingService:CreatePath(parameters)
path:ComputeAsync(root.Position, destination.Position)
return {path, path:GetWaypoints()}
end
local function chaseTarget(target)
local paths = getPath(target.PrimaryPart)
if paths[1].Status == Enum.PathStatus.Success then
for index, waypoint in pairs(paths[2]) do
humanoid:MoveTo(waypoint.Position)
if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid.Jump = true
end
if canSeeTarget(target) then
break
end
local timeOut = humanoid.MoveToFinished:Wait(0.5)
if not timeOut then
break
end
end
end
end
local function start(destination)
local paths = getPath(destination)
if paths[1].Status == Enum.PathStatus.Success then
local target = findTarget()
for index, waypoint in pairs(paths[2]) do
if target and target.Humanoid.Health > 0 then
if canSeeTarget(target) then
repeat
humanoid:MoveTo(target.PrimaryPart.Position)
until canSeeTarget(target) == false
else
chaseTarget(target)
end
else
humanoid:MoveTo(waypoint.Position)
humanoid.MoveToFinished:Wait()
end
end
else
humanoid:MoveTo(destination.Position - (root.CFrame.LookVector * 10))
end
end
local function patrol()
local waypoints = ai.Parent.Waypoints:GetChildren()
local randomNumber = math.random(1, #waypoints)
start(waypoints[randomNumber])
end
while wait(0.25) do
patrol()
end
Please help me : )