I made a single script for group of npcs but it only activates when i get near to a specific npc
I dont know what to do about it
heres the code
server script–
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local AI = script.Parent
local module = require(script.ModuleScript)
while true do
for i,v in pairs(workspace.Folder:GetChildren()) do
local target = module.findNearestPlayer()
if target then
v.Humanoid:MoveTo(target.Position)
end
task.wait(0)
end
end
module script–
local module = {}
local AI = script.Parent.Parent
module.findNearestPlayer = function()
for i,v in pairs(workspace.Folder:GetChildren()) do
local nearestPlayer = nil
local shortestDistance = 20
for i, plr in game.Players:GetPlayers() do
local character = plr.Character
if character then
local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
if humanoidRootPart then
local distance = (humanoidRootPart.Position - v.HumanoidRootPart.Position).Magnitude
if distance < shortestDistance then
shortestDistance = distance
nearestPlayer = humanoidRootPart
end
end
end
end
return nearestPlayer
end
end
return module
First of all you gotta remove the for i,v in pairs(workspace.Folder:GetChildren()) do in your findNearestPlayer function since you already doing a for i loop in your server script.
In your module script, the return statement inside the first for loop stops after checking players for one of the npc’s. Also, inside the module script, there isn’t a parameter that references an npc to check. What the server script is doing with the module script is just checking the same npc the same number of times there are npcs. To fix this, modify your module script like so:
local module = {}
module.findNearestPlayer = function(npc)
local nearestPlayer = nil
local shortestDistance = 20
for i, plr in game.Players:GetPlayers() do
local character = plr.Character
if character then
local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
if humanoidRootPart then
local distance = (humanoidRootPart.Position - npc.HumanoidRootPart.Position).Magnitude
if distance < shortestDistance then
shortestDistance = distance
nearestPlayer = humanoidRootPart
end
end
end
end
return nearestPlayer
end
return module
and with the server script, on the line that calls the function, put v in the parenthesis.