I would like to know if there is an objectively better / more efficient way to achieve the same functionality as the following code.
Note: This code is in a LocalScript located inside StarterPlayerScripts.
local NPCModule = require(script.Parent)
local Player = game.Players.LocalPlayer
local Character = game.Workspace:WaitForChild(Player.Name)
local Humanoid = Character:WaitForChild("Humanoid")
local NPCs = {}
for _, NPC in pairs(game.Workspace.NPCs:GetChildren()) do
table.insert(NPCs, NPC)
end
Humanoid.Changed:Connect(function()
for _, NPC in pairs(NPCs) do
local NPCPosition = NPC.HumanoidRootPart.CFrame.p
local CharacterPosition = Character.HumanoidRootPart.CFrame.p
local MaxDistance = 10
if (NPCPosition - CharacterPosition).magnitude <= MaxDistance then
--Do stuff
end
end
end)
