Hey, I want make a module script for finding the nearest player and use it everytime when I need it.
This is what I have seen so far but how can I import that in a module script?
I want also let it work with a if statement
and also how could I make this script work? While you helping me I am trying to do this myself
local npc_directory = game.Workspace['npc_folder'] --put the name of the folder here
local function ClosestHumanoid(player)
local players = game.Players:GetPlayers();
local npcs = npc_directory:GetChildren();
local closest = { humanoid = false, distance = math.huge } --where we will store the closest humanoid found so far, along with how far away it is
local character = player.Character or player.CharacterAdded:wait();
local root = character:WaitForChild('HumanoidRootPart', 1);
local to_check = npcs;
for _,PLAYER in pairs(players) do
if PLAYER.Character and PLAYER ~= player then
table.insert(to_check, PLAYER.Character)
end
end
for _,humanoid_model in pairs(to_check) do
local displacement = (humanoid_model .HumanoidRootPart.Position - root.Position).magnitude;
if displacement < closest.distance then
closest.distance = displacement;
closest.humanoid = humanoid_model:FindFirstChild('Humanoid');
end
end
return closest.humanoid
end
To put this function in a modulescript, you have to make a modulescript and put it somewhere (I recommend ServerStorage if multiple scripts are going to use it). If you open it it looks like this:
local module = {}
return module
you can rename ‘module’ to whatever you want. then you have to make a function in that moduleScript. There are multiple ways to do this. you can do this:
local module = {}
module.ClosestHumanoid = function()
-- the function here
end
return module
or you can do this
local module = {}
function module.ClosestHumanoid()
-- the function here
end
return module
if you want to use this function in another script, you first have to require it. That looks like this
local ModuleScript = require(path_to_module)
then you just have to call that function in that script
local ModuleScript = require(path_to_module)
local closestHumanoid = ModuleScript.ClosestHumanoid(player)
I don’t really know what you mean, but you can use if statements in moduleScripts and you can check the returned value of the function in the modulescript by doing this
local ModuleScript = require(path_to_module)
local closestHumanoid = ModuleScript.ClosestHumanoid(player)
if closestHumanoid then
-- do something
end