The best way to show npc's for nearest players?

Hi,
Im making a game and there are will be alot of NPC’s and i was thinking that there can be lags.

I think i need to create a script that will be showing to player only nearest to him nps’s.
So how i can check if player near to it? I will probably use local script for it :thinking:

local magnitude = (player.Character.HumanoidRootPart.Position - npc.HumanoidRootPart.Position).Magnitude

if magnitude <= 10 then --10 studs or less apart

--activate

end

Magnitude basically gets the distance between two things if you subtract their positions (in any order).

Here’s the DevHub documentation.

1 Like

You can either use magnitude, or get touching parts. So you would make a spherical part welded tot he player and constantly check with :GetTouchingParts. The sphere is as big as you want to be to detect NPC’s:
note that the spheres cancollide is set to false, anchored is also false, transparency is 1

local NPCs = {All the NPCs HumanoidRootParts}
local Part = -- the sphere
Part.Touched:Connect(function() end)
while true do
    local PartsTouched = Part:GetTouchingParts()
    for i, Part in pairs(PartsTouched) do
        if table.find(NPCs, Part) then
            --do somthing
        end
    end
end

An alternative to this is to just use magnitude, like @TheCarbyneUniverse suggested.


To make it easier, try looking into CollectionService

local CS = game:GetService("CollectionService")
local NPCs = CS:GetTagged("NPC")
local Part = -- the sphere
Part.Touched:Connect(function() end)
while true do
    local PartsTouched = Part:GetTouchingParts()
    for i, Part in pairs(PartsTouched) do
        if CS:HasTag(Part, "NPC") then
            --do somthing
        end
    end
end

why should i use a spherical part? what the difference beetween just blocks and spheres?

Since you want to detect NPCs in a certain radius, a sphere will make sure that it detects NPCs at a set length: