✓ Accepted answer
This is an example of where you can avoid writing a loop, which you should. The Teams should only update when a Player enters or leaves the game, and we have Events for those: PlayerAdded and PlayerRemoving.
The problem you're having is that GetChildren returns a Table, which you have to iterate over to actually get the Players to change their Teams. By the way, you should use the GetPlayers method here instead, as it will only ever return Player objects:
function setTeam(teamColor)
for _, player in ipairs(game.Players:GetPlayers()) do
player.TeamColor = BrickColor.new(teamColor)
end
end
game.Players.PlayerAdded:connect(function(plr)
wait()
setTeam("Bright blue")
end)
game.Players.PlayerRemoving:connect(function(plr)
plr.Character.AncestryChanged:wait()
setTeam("Bright blue")
end)
Now, this will change the Team of all Players to "Bright blue". That may not be what you want.
As for moving 1/3rd of the Players, we can calculate how many that is using the NumPlayers property of Players divided by three, round it down to get an integer, and then iterate over the Table differently:
function setTeam(team1, team2)
local plrs = math.floor(game.Players.NumPlayers/3)
local i = 1
for _, player in ipairs(game.Players:GetPlayers()) do
if i <= plrs then
player.TeamColor = BrickColor.new(team1)
else
player.TeamColor = BrickColor.new(team2)
end
i = i + 1
end
end
game.Players.PlayerAdded:connect(function(plr)
wait()
setTeams("Bright blue", "Bright red")
end)
game.Players.PlayerRemoving:connect(function(plr)
plr.Character.AncestryChanged:wait()
setTeams("Bright blue", "Bright red")
end)
2 comments
Is there a way to assign them without PlayerAdded
You can call the setTeams or setTeam function whenever you want to change the composition of the teams.