[BEST WAY] To make detect when a player gets near a zone roblox

Hey there, I hope your having a good day! So I was recently wondering what the best way to detect when a player gets near a part/zone, I know I could do something like this:

function findNearestPlayer(Position)
	local nearestPlayerDist = 0
	local nearestHRP = nil
	for _, player in pairs(game.Players:GetPlayers()) do
		local char = player.Character
		local HRP = char.HumanoidRootPart
		if (HRP.Position - Position).magnitude < 20 or (HRP.Position - Position).magnitude < nearestPlayerDist then
			nearestHRP = player.Character.HumanoidRootPart
	return nearestHRP

(This code was from my zombie follow script, not what this topic is about)

But the problem is that this requires a while loop to be created to constantly check when a player is near, now my question is: Will the cause performance issues?


I think you could just check when the player is moving ? and with that, you won’t need the while loop

If I understood you right,
By checking when the player moves, you could check if he gets close to certain zones

	if Humanoid.MoveDirection == Vector3.new() then return end
1 Like

Well yes, however I want this to detect if ANY player is near. Not just detection for only one player. Also I will no longer use this as for some reason when I tried to do the detection for my zone, at 41.5 Studs away I would have to get super close to the zone’s center, and at 41.6 Studs away it will detect me all the way at spawn (which is far btw). Now that I’m typing this, I think its cause my spawn is elevated lol. Anyways im using touched events now, so yeah…

1 Like

You could combine it within a CharacterAdded event for that, on the server.

Look into Region3s please! I absolutely love them and use them over Touched events every chance I get.


And using region3’s are inefficient.

Sure thing, I don’t know why I haven’t done this yet lol.

Why exactly is that, I thought they should be more efficient then touched events!

Then your logic is broken because calculating what is in a region3 every so called interval is not efficient.

Ah, you are talking about in this scenario. I thought you meant all around.

-- serverscript

    print(player, "is near zone")

-- localscript

local zone = Vector3.new(0, 4, -100)
local distance = 20
local near = false

    local position = workspace.CurrentCamera.Focus.Position
    local magnitude = (zone - position).Magnitude
    if near == false then
         if magnitude < distance then
            near = true
        if magnitude < distance then
            near = false

He could also probably mean that Region3s are inefficient all around because Region3s are actually inefficient all around. You should be using overlap params, raycasts or anything else that’s better.

1 Like