How to check the distance from multiple parts simultaneously

So I’m working on a NPC interaction and I’ll have multiple NPCs in my game. Currently, my code will only check the distance from one NPC. (because I have it in a never ending while loop)

Any thoughts on how I would accomplish checking the distance from all the NPCs at once?

A friend suggested using Coroutines, but I’ve never used those and am not exactly sure if that’d be my best strategy.

Any help would be much appreciated!


My current Code:
(ModuleScript called locally in PlayerScripts)

local Module = {}

local Player = game.Players.LocalPlayer
local PlayerGui = Player.PlayerGui
local Distance = 12

function Module.CheckQuest(Level)
    for _, Quest in pairs(game.Workspace[Level]:WaitForChild("Quests"):GetChildren()) do
        local Collider = Quest:WaitForChild("NPC")
    end
    while wait(.2) do
         if Player:DistanceFromCharacter(Collider.PrimaryPart.Position) <= Distance then
            print("Close 'nuff")
        end    
        
        if Player:DistanceFromCharacter(Collider.PrimaryPart.Position) > Distance then
            print("Too Far Away!")
        end    
    end
end

return Module

You can move your for loop into your while loop and look at the distance to the collider there.

Something like this should work:

function Module.CheckQuest(Level)
    while wait(.2) do
        for _, Quest in pairs(game.Workspace[Level]:WaitForChild("Quests"):GetChildren()) do
            local Collider = Quest:WaitForChild("NPC")
            if Player:DistanceFromCharacter(Collider.PrimaryPart.Position) <= Distance then
                print("Close 'nuff")
            else
                print("Too Far Away!")
            end
        end 
    end
end

This would loop over all of your quest NPCs each time the while loop runs. Effectively doing what you’re looking to achieve.

3 Likes

Ha. I did the reverse of that…Put the While Loop in the For Loop…Which was completely wrong.

What you showed should work! I’ll test it in a few minutes then let you know if it worked. :slight_smile:

Thanks!

Eyy! It worked! Thank you so much! :slight_smile:

1 Like