Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Efficiency in checking for position / magnitude?

So I'm trying to make a basic NPC-like dialog GUI appear when a player walks near a certain part. Only problem is, I feel as if my code is somewhat inefficient. I use a while loop and magnitude to compare the player's torso position, to the target part. Here's a brief example of what it looks like:

-- Services
local players = game:GetService("Players")

-- Client
local client = players.LocalPlayer
local mouse = client:GetMouse()
local char = client.Character or client.CharacterAdded:wait()
local torso = char:WaitForChild("Torso")

-- Workspace
local npc = workspace:WaitForChild("NpcPart")

-- Main loop
while wait(1) do
	if (torso.Position  - npc.Position).Magnitude < 10 then
		print("Player is in range")
	end
end

So this does work, however If i wanted a really vast amount of NPC objects, I feel like this could get messy and inefficient really quick. I've also heard about Region3, but I'm not sure if that would be a good choice either.

If someone knows a bit more about this than me and is willing to share, I'd appreciate it!

1 answer

Roblox's Dialog has a property called ConversationDistance which disables the Dialog until the Player's Character is within range. That's the baked-in solution.

If you are using a custom implementation of NPC dialogue, just check the magnitude whenever a Player attempts to initiate the dialogue (i.e clicks on the npc or shoots at it or something)

This discussion is preserved as it was. New answers, comments, and votes are closed.