Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I assigning players to unbalanced teams?

while true do
	game.Players:GetChildren().TeamColor = BrickColor.new ("Bright blue")
	wait(1)
end 

Can you fix the code and/or elaborate why what I wrote doesn't work? The code is intended to change a player's team to Bright blue.

Also if you know an efficient way to put a 1/3 of the players on one team and put the rest on the other that would be helpful.

1 answer

✓ 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) --1/3 to team1, 2/3 to 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

0

Is there a way to assign them without PlayerAdded

1

You can call the setTeams or setTeam function whenever you want to change the composition of the teams.

This discussion is preserved as it was. New answers, comments, and votes are closed.