I need an algorithm or method to detect when a player leaves or joins a team?
COMMUNITY QUESTION
How do I count players in a team?
2 answers
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)
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)
This discussion is preserved as it was. New answers, comments, and votes are closed.
