Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How to detect when a player leaves a region?

Asked by 6 years ago

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

01local Players = {} -- players in region gets stored into this table
02local AreaPart = workspace.Area
03 
04function createRegion3FromPart(part)
05    local Size = part.Size
06    local Position = part.Position
07    return Region3.new(Position-(Size/2), Position+(Size/2))
08end
09 
10function getPlayersInPart(part)
11    if part and part:IsA("BasePart") then
12        local newRegion = createRegion3FromPart(part)
13        local partsInRegion = workspace:FindPartsInRegion3(newRegion, nil, math.huge)
14        for i, v in pairs(partsInRegion) do
15            if game.Players:FindFirstChild(v.Parent.Name) then
View all 28 lines...
0
Why are you checking in line 11 is part is a BasePart? That's unnecessary as that is always true. User#19524 175 — 6y
0
What if I accidentally use a different instance thats not a BasePart? awesomeipod 607 — 6y
0
You won't though. User#19524 175 — 6y

1 answer

Log in to vote
0
Answered by
jaschutte 324 Moderation Voter
6 years ago

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.

01function getPlayersInPart(part)
02    if part and part:IsA("BasePart") then
03            local newRegion = createRegion3FromPart(part)
04            local partsInRegion = workspace:FindPartsInRegion3(newRegion, nil, math.huge)
05        local tempList = {} --this list resets each time
06            for i, v in pairs(partsInRegion) do
07                    if game.Players:FindFirstChild(v.Parent.Name) then
08                local player = game.Players[v.Parent.Name]
09                table.insert(tempList, player)
10                if not Players[player] then
11                            table.insert(Players, player)
12                end
13                    end
14            end
15        for k,v in pairs(tempList) do --loop over every player found in this single check
View all 21 lines...

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

1
Uhm, script, why do you look so wierd now.? I am sure I didn't write it like this, jaschutte 324 — 6y
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? IncredibleTeamAidan 104 — 4y
Ad

Answer this question