local function Follow() ---
local target = nil
local targetModel = nil
local shortestDistance = distance
for _, model in workspace:GetChildren() do
if model ~= script.Parent and model:FindFirstChild("Humanoid") and model:FindFirstChild("HumanoidRootPart") then
local parentnames = model.Parent.Name
print(model.Name , "Parent", parentnames) ---am trying to make the npc follow npcs that are in a folder but it doesn't work
if model.Parent:IsDescendantOf(workspace) and (parentnames == "Fightbacknpcs" or parentnames == "cops" or parentnames == "guncops" or parentnames == "NPCS") then
local humanoid = model.Humanoid
print("found a humanoid model")
if humanoid.Health > 0 then
local targetHRP = model.HumanoidRootPart
local dist = (targetHRP.Position - hrp.Position).Magnitude
if dist <= shortestDistance then
shortestDistance = dist
target = targetHRP
targetModel = model
end
end
end
end
end
workspace:GetChildren() gets only the initial children of the Instance, it doesn’t go lower.
If you want to go lower, then you can replace workspace:GetChildren() with workspace:GetDescendants(). This will return all of the descendants of the object, or in other words, every single child of the object, including ones that are children of other objects as long as they share the same ancestor as the object your calling the method on.
ive tryed that but it just makes my game extremely laggy since all npcs have this and its looped
Unfortunately this probably is the best fix, so that means you going to make some optimisation, if not already make the NPC’s run on the client and when a changed send a remote to the server and the server tells the rest of the client to make the change and if it is a game with guns maybe use unreaibleremoteevents, if that still makes it laggy you can do something like minecraft were it loads a certain amount of chucks but in your case NPC’s. Now only take my word with a grain of salt.