What's the cleanest method to detect something by range?

Basically I’m trying to make an automatic door like Adopt Me one which opens when the player is near, obviously using RunService.Heartbeat with a lot of doors would use a lot of memory which is bad so I’m wondering which is the cleanest method to achieve this.

you could use magnitude with a while loop

local door = workspace.door -- change to door's path
		local died = false
		local hum = char:WaitForChild("Humanoid")
			died = true
		while true do
			if died then break end
			if char then
				if (char.PrimaryPart.Position - door.Position).Magnitude <= 10 then
					-- script to open door

Well, this is a good method but sadly I specified this

obviously using RunService.Heartbeat(loop) with a lot of doors would use a lot of memory

Well you could do RunService.Heartbeat. But not for every door.

Loop through every door each .Hearbeat

  for _, v in pairs(doors) do
    -- thing

Or as @TheH0meLands suggested. You could do it by players, every heartbeat loop through the players

1 Like

oh well I thought you meant using heartbeat would cause an issue, not a loop. You’re really out of luck then sorry bud

1 Like

You didn’t define Magnitude


That makes no sense, I already said that looping could use excesive script memory, maybe the best I can do is storing every door in a table.

there’s no way to do something like this without a loop/heartbeat. If you dont want to do it then you’re out of luck

1 Like

Not really, doing .Heartbeat alot would cause high memory.

This method uses one .Heartbeat.

If you really wanna save memory. Use .Touched

1 Like

Region3 would probably be your best bet

Region3 isn’t deprecated as it is used for terrain functions. But yes, @CodingDominus is using the deprecated thing of Region3, checking if an instance is within an area.

Scouting the wiki I found this



Well you can split up all the doors into regions and only check doors in that region.

I would recommend doing all of it on the client and sending information to the server if needed only once passed to reduce server load. So have the client decide when the door opens, then have them tell the server which checks if they are within reasonable distance. Going through every player once like you would do on client usually isn’t a big issue. Honestly that’s how I’d do it unless I ended up getting really laggy at the fault of that script. In that case I would implement what I said above where I’d split up the doors and only check doors in the same area as the player. I would still run this in heartbeat or a while loop with a longer delay depending on how immediate I want the doors to be.

1 Like

I will mark this as solution as you gived me an idea, basically using the whitelist for the folder which contains every door instance, it will use less memory and will find every door near to the player using the cleanest way which is Roblox backend.

1 Like