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

How do I count players in a team?

Asked by 10 years ago

I need an algorithm or method to detect when a player leaves or joins a team?

2 answers

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

It may be satisfactory to just get the players on each team.

We just filter all of the players by matching their TeamColor to a Team's:

function getTeam(team)
    local players = game.Players:GetPlayers();
    local teamPlayers = {};
    for _, player in pairs(players) do
        if player.TeamColor == team.TeamColor then
            table.insert(teamPlayers, player);
        end
    end
    return teamPlayers;
end

For the actual moment of entering and leaving, we can listen in to PlayerLeaving and PlayerAdded.


function PlayerLeftTeam(player,teamcolor) -- Do whatever end function PlayerLeaving(player) PlayerLeftTeam(player, player.TeamColor); end game.Players.PlayerLeaving:connect(PlayerLeaving);

(and the same for PlayerAdded)

Ad
Log in to vote
1
Answered by
Ekkoh 635 Moderation Voter
10 years ago

To add on to Blue's response, that function wouldn't fire when the player switches teams. So this is what I'd do.

function PlayerLeftTeam(plr, team)
    print(plr.Name .. " left " .. team.Name .. " team.")
    -- code
end

function PlayerAdded(plr)
    local lastTeam = plr.TeamColor
    plr.Changed:connect(function(p)
        if p == "TeamColor" then
            PlayerLeftTeam(plr, lastTeam)
            lastTeam = plr.TeamColor
        end
    end)
end

function PlayerLeaving(plr)
    PlayerLeftTeam(plr, plr.TeamColor)
end

Game.Players.PlayerAdded:connect(PlayerAdded)
Game.Players.PlayerLeaving:connect(PlayerLeaving)

Answer this question