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

How do I split players into two teams? I know #, how can I use it?

I first get all the players and put then into one table.

plrs = {}
for i, player in pairs(game.Players:GetPlayers()) do
	if player then
		table.insert(plrs, player)
	end
end

But then how can I split that table in half and create two seperate tables for the players? Each with half the players.

2 answers

So, first let's get a table of all the players:

local plrs = game.Players:GetChildren()

Now, let's define two teams called Red Team and Blue Team:

local redTeam = {}
local blueTeam = {}

So, we need to divide the teams in half. We also need to use math.floor to get no decimals in case there is an odd number of players.

local plrsOnEachTeam = math.floor(plrs / 2)

Now, we put that amount of people on each team:

for i = 1,plrsOnEachTeam,1 do
	table.insert(redTeam,#redTeam + 1,plrs[1])
	table.remove(plrs,1)
end

for i =1,plrsOnEachTeam,1 do
	table.insert(blueTeam,#blueTeam + 1,plrs[1])
 	table.remove(plrs,1)
end

--In case there is a leftover player
if #plrs == 1 then
	table.insert(redTeam,#redTeam + 1,plrs[1])
	table.remove(plrs,1)
end

Hope this helped!

It's easier to use the modulus in my opinion. If you mod any number by 2 you'll get either 0 or 1. If the mod was 0, then assign to the first team and if it was 1 then assign to the other team.

Local Players = game:GetService("Players")

for i, v in pairs(Players:GetChildren()) do
	if i % 2 == 0 then
		v.Team = TEAM_1
	elseif i % 2 == 1 then
		v.Team = TEAM_2
	end
end

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