How to detect if player leaves region

Hello! I’ve been learning region or GetPartsBoundsInBox; it’s useful. However, I am curious on how do I detect if a player left the region? thank you.

local RegionPart = workspace:WaitForChild('Part')

local params = OverlapParams.new()
params.FilterDescendantsInstances = {RegionPart}
params.FilterType = Enum.RaycastFilterType.Exclude
params.MaxParts = 5

while true do
	task.wait()
	local PartsInRegion = workspace:GetPartBoundsInBox(CFrame.new(RegionPart.CFrame.X, RegionPart.CFrame.Y, RegionPart.CFrame.Z), Vector3.new(RegionPart.Size.X, RegionPart.Size.Y, RegionPart.Size.Z), params)
	
	local CharacterTable = {}
	
	for i, part in pairs(PartsInRegion) do
		if part.Parent:FindFirstChildOfClass("Humanoid") and not table.find(CharacterTable, part.Parent) then
			table.insert(CharacterTable, part.Parent)
			print(CharacterTable)
		end
		
	end

	
	params:AddToFilter(CharacterTable)

end
3 Likes

You could check which players are in the region and see if they’re in the CharacterTable. If they aren’t in the region but are in the CharacterTable, they have left.

1 Like

Can I have a script demonstration?

This should be pretty easy, just use your current script, but you could preferentially have two tables, the table of the players in the region previously, and create a new table of the current players, compare those two tables, if there’s any players in the table previously that aren’t there now, you know a player left. And you can call a function or do some work. Here’s an example:

local RegionPart = workspace:WaitForChild('Part')

local params = OverlapParams.new()
params.FilterDescendantsInstances = {RegionPart}
params.FilterType = Enum.RaycastFilterType.Exclude
params.MaxParts = 5

local currentCharacters = {}

while task.wait() do
	local PartsInRegion = workspace:GetPartBoundsInBox(CFrame.new(RegionPart.CFrame.X, RegionPart.CFrame.Y, RegionPart.CFrame.Z), Vector3.new(RegionPart.Size.X, RegionPart.Size.Y, RegionPart.Size.Z), params)
	local newCharacters = {}

	for _, part in PartsInRegion do
		if part.Parent:FindFirstChildOfClass("Humanoid") and not table.find(CharacterTable, part.Parent) then
			table.insert(newCharacters, part.Parent)
		end
	end

	for _, oldCharacter in currentCharacters do
		if not table.find(newCharacters, oldCharacter) then
			-- do some work here for the left character
		end
	end

	currentCharacters = newCharacters
end

This code is NOT tested.

2 Likes

dunno if this is applicable here but i think zoneplus has a zone left function

2 Likes

I see…lIll go check it out! Thanks for the recommendation!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.