So basically I'm trying to make a simple AI that has priorities
Priorities 1- Light 2- Sound 3- Humans
But for some reason the AI just walks off the earth and ignores them all Here's my script:
local NPC = script.Parent local Humanoid = NPC:WaitForChild("Humanoid") local Rootpart = NPC:WaitForChild("HumanoidRootPart") local DetectionDistance = 50 local GOTO = nil local Object = nil UpdateAI = coroutine.create(function() while wait(0.025) do ------------ if GOTO == nil then GOTO = Rootpart end ------------ if Object == nil or GOTO == nil then Object = nil GOTO = Rootpart end ------------ if GOTO and Object then local CheckDistance = DetectionDistance if Object:IsA("Sound") and Object.Volume >= 5 then CheckDistance = DetectionDistance * 2 end if (Rootpart.Position - GOTO.Position).Magnitude > CheckDistance then Object = nil GOTO = nil end end ------------ if GOTO then Humanoid:Move(GOTO.Position) end ------------ for i,e in pairs(workspace:GetDescendants()) do ------------------------ --Lights if e:IsA("Light") and e.Parent:IsA("BasePart") and e.Enabled == true then if (Rootpart.Position - e.Parent.Position).Magnitude <= DetectionDistance then Object = e GOTO = e.Parent end --Sounds elseif e:IsA("Sound") and e.Parent:IsA("BasePart") and e.Playing == true then local CheckDistance = DetectionDistance if e.Volume >= 5 then CheckDistance = DetectionDistance * 2 end if (Rootpart.Position - e.Parent.Position).Magnitude <= CheckDistance then if Object:IsA("Light") then return end Object = e GOTO = e.Parent end --Humans elseif e:IsA("Model") and e:FindFirstChild("HumanoidRootPart") and e.PrimaryPart then if Object == nil then if (Rootpart.Position - e.PrimaryPart.Position).Magnitude <= DetectionDistance then Object = e GOTO = e.PrimaryPart end end end ------------------------ end ------------ end end) coroutine.resume(UpdateAI)
workspace:GetDescendants()
Why? Because :GetDescendants()
iterates through every instance in the workspace. Imagine having hundreds of thousands of instances in the workspace and iterating through all of that? It will take a long time, and the response won't be fast. That's why it's better you use CollectionService for your Lights.
Your if
statements are messy. Too many ifs could make your code confusing not just for other people but for you as well! You're also changing the values GOTO and Object so many times; can't figure out why or what's really going on.
I can't really give you a code that works since I'm having a hard time reading it. But try minimizing those methods.
For my final suggestion, change Humanoid:Move(GOTO.Position)
to Humanoid:MoveTo(GOTO.Position)
in line 44.