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.

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
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.

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.

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