Hey! I’m currently making a dungeon crawler and have been playing around with an enemy AI system I made. Currently, it works perfectly and has been implemented into monsters, undenounced to me that the enemy will stop patrolling (moving to random waypoints) the moment the person they’re chasing dies.
Problem: The AI breaks and refuses to move once the player they’re chasing dies. There is nothing being printed in the output menu.
Code:
local Enemy = script.Parent
local humanoid = script.Parent.Humanoid
local PathfindingService = game:GetService("PathfindingService")
script.Parent.PrimaryPart:SetNetworkOwner(nil)
-- Config Settings
local Config = Enemy:WaitForChild("Config")
local MinRange = 5
local CanPatrol = Config:WaitForChild("Patrols")
local function findTarget()
local players = game.Players:GetPlayers()
local maxDistance = 30 -- 10,000
local nearestTarget
for index, player in pairs(players) do
if player.Character then
local target = player.Character
local distance = (script.Parent.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
if distance < maxDistance then
nearestTarget = target
maxDistance = distance
end
end
end
return nearestTarget
end
local function getPath(destination)
local pathParams = {
["AgentHeight"] = 6,
["AgentRadius"] = 5,
["AgentCanJump"] = false
}
local path = PathfindingService:CreatePath(pathParams)
path:ComputeAsync(Enemy.HumanoidRootPart.Position, destination.Position)
return path
end
local function attack(target)
local distance = (Enemy.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
if distance > MinRange then
humanoid:MoveTo(target.HumanoidRootPart.Position)
humanoid.WalkSpeed = 10
elseif distance <= MinRange then
humanoid.WalkSpeed = 0
else
return
end
end
local function walkTo(destination)
local path = getPath(destination)
if path.Status == Enum.PathStatus.Success then
for index, waypoint in pairs(path:GetWaypoints()) do
local target = findTarget()
if target then
print("TARGET FOUND", target.Name)
attack(target)
break
else
humanoid:MoveTo(waypoint.Position)
humanoid.MoveToFinished:Wait()
end
end
else
humanoid:MoveTo(destination.Position - (Enemy.HumanoidRootPart.CFrame.LookVector * 10))
end
end
local function patrol()
if CanPatrol.Value == true then
local waypoints = Enemy.Parent:WaitForChild("PatrolPoints"):GetChildren()
local randomNum = math.random(1, #waypoints)
walkTo(waypoints[randomNum])
else
local target = findTarget()
if target then
attack(target)
end
end
end
while wait() do
patrol()
end
If you wish to replicate this problem simply insert an R6 rig, make some parts in a folder called “PatrolPoints”, place both the PatrolPoints folder and the R6 rig into another folder naming it whatever you’d like, and inside of the R6 rig make a configuration called “Config” and make a bool called “Patrols” inside. Make sure to set it to true!