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

How to detect when a player leaves a region?

I know how to check if a player enters a region but can't figure out when they leave it.

local Players = {} -- players in region gets stored into this table
local AreaPart = workspace.Area

function createRegion3FromPart(part)
	local Size = part.Size
	local Position = part.Position
	return Region3.new(Position-(Size/2), Position+(Size/2))
end

function getPlayersInPart(part)
	if part and part:IsA("BasePart") then 
		local newRegion = createRegion3FromPart(part)
		local partsInRegion = workspace:FindPartsInRegion3(newRegion, nil, math.huge)
		for i, v in pairs(partsInRegion) do 
			if game.Players:FindFirstChild(v.Parent.Name) then 
				local player = game.Players[v.Parent.Name]
				table.insert(Players, player)
			end
		end
	end
end

while true do
	for i, v in pairs(Players) do
		print(tostring(v))
	end
	getPlayersInPart(AreaPart) wait(1);
end

3 comments

0

Why are you checking in line 11 is part is a BasePart? That's unnecessary as that is always true.

0

What if I accidentally use a different instance thats not a BasePart?

0

You won't though.

1 answer

I have created a second table which gets reset every time. This was we can check if all players that where in the area a couple of minutes ago, still are here.

function getPlayersInPart(part)
	if part and part:IsA("BasePart") then 
        	local newRegion = createRegion3FromPart(part)
       		local partsInRegion = workspace:FindPartsInRegion3(newRegion, nil, math.huge)
		local tempList = {} --this list resets each time
       		for i, v in pairs(partsInRegion) do 
            		if game.Players:FindFirstChild(v.Parent.Name) then 
				local player = game.Players[v.Parent.Name]
				table.insert(tempList, player)
				if not Players[player] then
              				table.insert(Players, player)
				end
            		end
        	end
		for k,v in pairs(tempList) do --loop over every player found in this single check
			if not Players[v] then --if player hasn't been found which was found earlier, 
				table.remove(Players, v) --remove the player.
			end
		end
	end
end

I hope this helps! Message me if you encounter errors.

2 comments

1

Uhm, script, why do you look so wierd now.? I am sure I didn't write it like this,

0

Hi, I used this script, but it is coming up with error "Script:26: invalid argument #2 to 'remove' (number expected, got Instance)" line 17 on your script, any ideas how to solve?

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