How to detect if part has left area with :GetPartsInPart()?

I’m working on a script to detect when a part with a certain name has entered or left a zone with :GetPartsInPart(). So far I got it to detect when the part has entered but I can’t seem to get it to detect when the part leaves.

I’ve tried using table.find for detecting when the part leaves the zone but it doesn’t work.

while task.wait() do
local ColorBrick = script.Parent.ColorBrick
local Zone = workspace:GetPartsInPart(script.Parent.Zone)
for i, v in pairs(Zone) do
	if v.Name == "ActivationPart" then
		ColorBrick.Color = Color3.fromRGB(255, 0, 0)		
		end

		if not table.find(Zone, "ActivationPart") then
			print("Left The Area")	
		end
	end
end
1 Like

I would do it like this, using the second argument of GetPartsInPart

local ActivationParts = {}

local OP = OverlapParams.new()
OP.FilterDescendantsInstances = ActivationParts
OP.FilterType = Enum.RaycastFilterType.Whitelist
OP.MaxParts = 1

while task.wait() do
	local ColorBrick = script.Parent.ColorBrick
	if #workspace:GetPartsInPart(script.Parent.Zone, OP) > 0 then
		ColorBrick.Color = Color3.fromRGB(255, 0, 0)
	else
		print("Left The Area")	
	end
end

In ActivationParts would go all the parts that have the name ActivationPart and verify the quantity.

3 Likes

A quick note to op,
At this point we don’t know if the part has left. All we know is the part is not in the area.
If you need a point in time that says it now left you can do:

elseif ColorBrick.Color == Color3.new(1,0,0) then
        --it has left the area so set the color to the normal color
        ColorBrick.Color = Color3.new(1,0,1)
        print("Left the area")
    else
        print("Not in area")
    end
3 Likes